【问题标题】:Namespace in XML selects everything using XSLTXML 中的命名空间使用 XSLT 选择所有内容
【发布时间】:2016-01-17 19:00:27
【问题描述】:

当命名空间 xmlns="http://tempuri.org/BaseSchema" 不存在时,以下 XSLT 完美地从给定 XML 中选择节点。

问题:当名称空间xmlns="http://tempuri.org/BaseSchema" 出现在 XML 中时,就像真正的问题一样,XSLT 会从 XML 中选择所有内容,而不是 XSLT 中提到的节点。

无法修改输入文件以删除命名空间。有谁知道如何忽略或抑制命名空间的影响。

XML

<event xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/BaseSchema" >
    <name>Pancake</name>
    <categories>
    <category>community</category>
     </categories>
     <venue>
    <name>fatzcafe</name>
        <city>NYC</city>
    <venue_type>
             <name>Lounge</name>
             <cuisine>Thai</cuisine>
        </venue_type>
      </venue>
</event>

XSLT

<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/BaseSchema">
 <xsl:output method="text" encoding="UTF-8" />

  <xsl:template match="/event">
     <xsl:apply-templates select="venue/venue_type"/>
  </xsl:template>

  <xsl:template match="/venue_type">
     <xsl:value-of select="name" />
     <xsl:value-of select="cuisine" />
  </xsl:template>
</xsl:stylesheet>

【问题讨论】:

标签: xml xslt


【解决方案1】:

是的,它有点在 XSLT 1.0 中真的很无聊......你必须明确地将你的命名空间绑定到一个前缀,并在你的 templates match=apply-templates select= 的 XPath 中使用它。 .

重构后的 XSLT 应如下所示:

<xsl:stylesheet version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xmlns:t="http://tempuri.org/BaseSchema">
 <xsl:output method="text" encoding="UTF-8" />

  <xsl:template match="/t:event">
     <xsl:apply-templates select="t:venue/t:venue_type" />
  </xsl:template>

  <xsl:template match="/t:venue_type">
     <xsl:value-of select="t:name" />
     <xsl:value-of select="t:cuisine" />
  </xsl:template>
</xsl:stylesheet>

【讨论】:

  • 非常感谢!它有帮助。想知道是否还有其他快捷方式,例如在标题标签本身中添加一些内容。
  • @Hodor XSLT 1.0 中没有。在 XSL-T 2.0 中,您可以使用 xpath-default-namespace,请参阅 this question
  • 谢谢。但是选择一个节点会选择它的兄弟姐妹和孩子的值。在上面的 XSLT 中,如果删除了 &lt;xsl:value-of select="t:cuisine" /&gt;,则在结果答案中仍然可以看到美食。或任何属于 的孩子的东西都可以看到。你能指出我在这里可能遗漏了什么吗?
  • 解决了我对上述评论的疑问。将 &lt;xsl:template match="/t:venue_type"&gt; 更改为 &lt;xsl:template match="t:venue_type"&gt; 更正了该问题。谢谢。
  • @Hodor 如果您的问题已经解决,请接受答案。谢谢。
猜你喜欢
  • 2018-05-30
  • 1970-01-01
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
  • 2013-04-11
  • 2010-09-21
  • 2014-06-11
  • 1970-01-01
相关资源
最近更新 更多