我对XSL很新,需要帮助解决转换问题.我有一个由XSD描述的XML文件.我使用XSL文件将XML转换为HTML.我想在XML文件中引用XSD,但是当我这样做时,XML不会被转换.
示例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>
Run Code Online (Sandbox Code Playgroud)
示例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>
Run Code Online (Sandbox Code Playgroud)
示例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>
Run Code Online (Sandbox Code Playgroud)
在XML中,如果我使用注释掉的root标签,Firefox和Chrome不会转换xml.但是,如果我只使用普通的<root>标签,那么转换就可以了.
任何人都可以解释为什么在我的XML中引用XSD时不会发生XSL转换?任何帮助表示赞赏!
<!-- <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://localhost" xsi:schemaLocation="http://localhost example.xsd"> -->
Run Code Online (Sandbox Code Playgroud)
这与使用XML Schema无关.问题是您指定了默认命名空间.
在默认命名空间中使用XPath表达式来表示节点名称是最大的XPath FAQ.
请在xpath和xslt标签中搜索"默认命名空间",你会找到很多好的答案.
XSLT的解决方案是声明一个带有一些前缀(比如"x")和namespace-uri的命名空间,它与XML文档中默认命名空间的namespace-uri相同.然后在任何XPath表达式中使用x:name而不是name.
因此,您的XSLT代码变为:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:x="http://localhost" exclude-result-prefixes="x" >
<xsl:template match="/">
<ul>
<xsl:for-each select="x:root/x:element">
<li>
<xsl:value-of select="."/>
</li>
</xsl:for-each>
</ul>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
当应用于提供的带有未注释<root>元素的XML文档时:
<root xmlns="http://localhost"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://localhost example.xsd">
<element>Element 1</element>
<element>Element 2</element>
<element>Element 3</element>
</root>
Run Code Online (Sandbox Code Playgroud)
产生了想要的正确结果:
<ul>
<li>Element 1</li>
<li>Element 2</li>
<li>Element 3</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5142 次 |
| 最近记录: |