无法匹配具有命名空间属性的XML元素

时间:2010-09-01 05:20:09

标签: xslt

如果我要使用xslt在下面的xml中插入一段文本,条件语句会怎么样?

<items xmlns="http://mynamespace.com/definition">
    <item>
        <number id="1"/>
    </item>
    <item>
        <number id="2"/>
    </item>
    <!-- insert the below text -->
    <reference>
        <refNo id="a"/>
        <refNo id="b"/>
    </reference>
    <!-- end insert -->
</items>

这就是我的xsl目前的样子(条件错误......):

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns="http://mynamespace.com/definition"
    version="1.0">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:param name="addRef">
        <reference>
            <refNo id="a"/>
            <refNo id="b"/>
        </reference>
    </xsl:param>
    <xsl:template match="node()|@*" name="identity">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <!-- here is where the condition got stuck... -->
    <xsl:template match="/items[namespace-url()=*]/item[position()=last()]">
        <xsl:call-template name="identity"/>
        <xsl:copy-of select="$addRef"/>
    </xsl:template>
</xsl:stylesheet>

我想在最底层之后添加引用部分,但我不知道如何绕过匹配具有(显式)命名空间的元素。

感谢。

2 个答案:

答案 0 :(得分:5)

更好,更优雅的解决方法是使用命名空间的前缀。我更喜欢使用null默认命名空间,并为所有已定义的命名空间使用前缀。

fn:local-name()上的匹配将匹配所有命名空间中节点的本地名称。如果您的命名空间使用前缀,则匹配条件中需要的只是my:item[last()]

<强>输入:

<?xml version="1.0" encoding="UTF-8"?>
<items xmlns="http://mynamespace.com/definition">
  <item>
    <number id="1"/>
  </item>
  <item>
    <number id="2"/>
  </item>
</items>

<强> XSLT:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
  xmlns:my="http://mynamespace.com/definition">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

  <xsl:param name="addRef">
    <!-- We set the default namespace to your namespace for this
         certain result tree fragment. -->
    <reference xmlns="http://mynamespace.com/definition">
      <refNo id="a"/>
      <refNo id="b"/>
    </reference>
  </xsl:param>

  <xsl:template match="node()|@*" name="identity">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="my:item[last()]">
    <xsl:call-template name="identity"/>
    <xsl:copy-of select="$addRef"/>
  </xsl:template>

</xsl:stylesheet>

<强>输出:

<?xml version="1.0" encoding="UTF-8"?>
<items xmlns="http://mynamespace.com/definition">
  <item>
    <number id="1"/>
  </item>
  <item>
    <number id="2"/>
  </item>
  <reference>
    <refNo id="a"/>
    <refNo id="b"/>
  </reference>
</items>

答案 1 :(得分:0)

试试这个:

match="//*[local-name()='items']/*[local-name()='item'][position()=last()]"
相关问题