I am fairly new to XSL and need help with a transformation issue. I have an XML file that is described by an XSD. I use an XSL file to transform the XML into HTML. I want to reference the XSD in the XML file, but when I do the XML doesn’t get transformed.
Example XML:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="example.xsl"?>
<root>
<!--
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://localhost" xsi:schemaLocation="http://localhost example.xsd">
-->
<element>Element 1</element>
<element>Element 2</element>
<element>Element 3</element>
</root>
Example XSL:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<ul>
<xsl:for-each select="root/element">
<li><xsl:value-of select="."/></li>
</xsl:for-each>
</ul>
</xsl:template>
</xsl:stylesheet>
Example XSD:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://localhost"
xmlns="http://localhost"
elementFormDefault="qualified">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="element" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
In the XML, if I use the commented out root tag, Firefox and Chrome do not transform the xml. If I just use the plain <root> tag, however, the transformation happens fine.
Can anyone explain why the XSL transformation doesn’t happen if I reference the XSD in my XML? Any help is appreciated!
This has nothing to do with using an XML Schema. The problem is that you specify a default namespace.
Using XPath expressions for node names in a default namespace is the biggest XPath FAQ.
Please, search the xpath and xslt tags for “default namespace” and you’ll find many good answers.
The solution for XSLT is to declare a namespace with some prefix (say “x”) and namespace-uri that is the same as the namespace-uri of the default namespace in the XML document. Then in any XPath expression use
x:nameinstead ofname.Thus your XSLT code becomes:
and when applied on the provided XML document with uncommented
<root>element:the wanted, correct result is produced: