我正在尝试习惯XSLT,并且我理解命名空间的原因,但我只是尝试将本地XML文件转换为本地应用程序使用。
我正在尝试转换此处找到的文件:http://uscodebeta.house.gov/download/releasepoints/us/pl/113/31/xml_usc01@113-31.zip
使用此代码:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" name="xml"/>
<xsl:template match="//title">
<xsl:for-each select="section">
<xsl:variable name="href"><xsl:value-of select="ancestor::title/num/@value" />-<xsl:value-of select="ancestor::chapter/num/@value" />-<xsl:value-of select="num/@value" />.xml</xsl:variable>
<xsl:result-document href="$href">
<xsl:element name="structure">
<xsl:element name="unit">
<xsl:attribute name="label">title</xsl:attribute>
<xsl:attribute name="identifier">
<xsl:value-of select="ancestor::title/num/@value" />
</xsl:attribute>
<xsl:attribute name="order_by">
<xsl:value-of select="ancestor::title/num/@value" />
</xsl:attribute>
<xsl:attribute name="level">1</xsl:attribute>
<xsl:value-of select="ancestor::title/num" /> <xsl:value-of select="ancestor::title/heading"/>
</xsl:element>
</xsl:element>
</xsl:result-document>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
进入这里找到的XML示例: https://github.com/statedecoded/statedecoded/wiki/XML-Format-for-Parser
这只是第一个元素的转换,但是当在命令行上运行Saxon时,我收到警告:
Warning: SXXP0005: The source document is in namespace http://xml.house.gov/schemas/uslm/1.0, but all the template rules match elements in no namespace
,输出是纯文本而不是XML标记。
非常感谢任何帮助。
由于
答案 0 :(得分:6)
由于您使用的是XSLT 2.0,因此可以在xpath-default-namespace
上添加xsl:stylesheet
属性。有关详细信息,请参阅http://www.w3.org/TR/xslt20/#standard-attributes。
例如:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xpath-default-namespace="http://xml.house.gov/schemas/uslm/1.0">
您还可以选择使用*
作为路径中每个元素的前缀。如果你的样式表增长,那最终可能会有很多工作。
示例:
ancestor::*:title/*:num
完整示例:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xpath-default-namespace="http://xml.house.gov/schemas/uslm/1.0">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:apply-templates select="@*|node()"/>
</xsl:template>
<xsl:template match="section">
<xsl:result-document href="{ancestor::title/num/@value}-{ancestor::chapter/num/@value}-{num/@value}.xml">
<structure>
<unit label="title" identifier="{ancestor::title/num/@value}"
order_by="{ancestor::title/num/@value}" level="1">
<xsl:value-of select="concat(ancestor::title/num,' ',ancestor::title/heading)"/>
</unit>
</structure>
</xsl:result-document>
</xsl:template>
</xsl:stylesheet>