when working with XML files with non-default namespaces and XSL files, what's the proper way to write XPath expressions that .NET will understand?

StackOverflow https://stackoverflow.com/questions/14690009

Question

I'm aware that when it comes to .NET (or at least the version of .NET I'm on), if I want to query data from an XML document that has a non-default namespace, I have at least two choices:

1. use the local-name() function before referencing a
node in the xpath expression.

2. work with the XmlNamespaceManager class and assign prefixes
that then need to be referenced in the xpath expression.

Lately I have been working with the XSLCompiledTransform class, and have experienced similar problems when it comes to reading data from XML files with non-default namespaces.

Since the people who will be writing the actual XSL files might not know that they need to use the local-name() function, and have no control over the XML files they will be working with, what can I do, codewise, in order to endure that xpath expressions of the form (/node0/node1/node2/etc) are interpreted properly by the XSLCompiledTransform class?

Was it helpful?

Solution

If the people writing the XSLT code don't know what namespaces will be used in the XML instances, then they are working in the dark - it's much the same (in fact exactly the same) as not knowing what local names will be used, because the element name is in two parts, a URI and a local name, and you need to know both. If you don't know the full name in advance, you can always select elements by wildcard and discover their name - which is essentially what you are doing when you use local-name() - but that's hard work.

OTHER TIPS

Generally the proper practice is to assign prefixes to the namespaces that will be used and use those, whether it be in an XSLT or in an XmlNamespaceManager. Using local-name() to skirt around namespaces when you don't have to is rather hackish.

I'm somewhat confused by the latter part of your question, and your requirements. What kind of XPaths are you going to be using with the XslCompiledTransform class? Are you referring to the XPaths in the XSLT itself?

The thing about namespaces is that as long as the URIs match up, the prefixes can be anything. So your comment about "have no control over the XML files they will be working with" may be unwarranted concern. For example, if the input XML looks like this:

<aa:root xmlns:aa="http://my.namespace.com">
   <aa:child>Hello!</aa:child>
</aa:root>

You can have an XSLT like this:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:bb="http://my.namespace.com">
    <xsl:template match="bb:root">
       <xsl:value-of select="bb:child" />
    </xsl:template>
</xsl:stylesheet>

and everything will work fine, because the namespace URIs match. This is far preferable to having XSLTs littered with local-name()s.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top