Trouble matching XML elements that has namespace attribute

后端 未结 2 457
小蘑菇
小蘑菇 2021-01-23 22:57

How would the conditional statement look like if I\'m to insert a section of text into the xml below using xslt?



        
相关标签:
2条回答
  • 2021-01-23 23:35

    A better, and more elegant, way to solve this would be to use a prefix for your namespace. I prefer working with a null default namespace and using prefixes for all defined namespaces.

    Matching on fn:local-name() would match on the local name of the node in all namespaces. All that's needed in your matching condition if using a prefix for your namespace is my:item[last()].

    Input:

    <?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>
    

    Output:

    <?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 讨论(0)
  • 2021-01-23 23:54

    Try this:

    match="//*[local-name()='items']/*[local-name()='item'][position()=last()]"
    
    0 讨论(0)
提交回复
热议问题