I have the following xml file:
<DataConfiguration
xmlns="http://www.mysite.com/namespace"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.mysite.com/namespace/DataConfiguration.xsd">
<rule>
<if>
...
</if>
<then>
...
</then>
</rule>
</DataConfiguration>
which I want to parse using the following xslt:
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xsi="http://www.w3开发者_开发知识库.org/2001/XMLSchema-instance"
xmlns:doc="http://www.mysite.com/namespace"
exclude-result-prefixes="xsi">
<xsl:output omit-xml-declaration="yes"/>
<xsl:output method="text"/>
<xsl:template match = "/">
<xsl:for-each select="//rule">
<xsl:for-each select="if/*">
...
</xsl:for-each>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
The xslt works as expected but when I add the xmlns attribute to the top element of the xml it fails to find the xml elements. I saw some related questions on this site but still didn't figure out how to solve my specific problem. I tried to add doc: to the select as suggested here but it didn't help. Maybe it's because I'm using // ? Any other way to do these queries ?
Any other suggestion how to solve this ?
This is the biggest XPath XSLT FAQ. Just search: "XPath default namespace"
Very briefly:
Change:
<xsl:for-each select="//rule">
<xsl:for-each select="if/*">
...
</xsl:for-each>
</xsl:for-each>
To:
<xsl:for-each select="//doc:rule">
<xsl:for-each select="doc:if/*">
...
</xsl:for-each>
</xsl:for-each>
The reason for the observed confusing problem is that in XPath any unprefixed name is considered to be in "no namespace".
Therefore, select="//rule"
doesn't select any element in a document that is in a default namespace -- there is no element named rule
that is in no namespace.
Instead, the XPath expression must contain prefixed names and the prefix must be associated with the default namespace -- as done in the above solution.
精彩评论