2010-09-01 85 views
1

如果要使用xslt将一段文本插入到xml中,条件语句将如何显示?匹配具有名称空间属性的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> 

我想最底端的后添加的参考部分,但我得到了坚持如何避免匹配具有(显式)名称空间的元素。

谢谢。

回答

0

试试这个:

match="//*[local-name()='items']/*[local-name()='item'][position()=last()]" 
5

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

匹配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> 
+0

好的解决方案。 +1。 – 2010-09-01 12:59:14

+0

T:+1好答案。这是要走的路。 – 2010-09-01 13:53:32

+0

谢谢,你们俩! – 2010-09-01 14:07:26

相关问题