Problem with XML elements that have a namespace attribute

What would a conditional statement look like if I have to insert a section of text in the xml below using xslt?

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

Here's what my xsl looks like at the moment (the condition is wrong ...):

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

I wanted to add a reference section after the very bottom, but I was stuck on how to get around the corresponding element that has a (explicit) namespace.

Thanks.

+1
source share
2 answers

Try the following:

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

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

Matching fn:local-name() will match the local name of the node in all namespaces. All that is required in your consent, if a prefix is ​​used 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> 

Conclusion:

 <?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> 
+5
source

Source: https://habr.com/ru/post/907050/


All Articles