首页 > 解决方案 > 由于命名空间“xmlns:ns0”,无法使用 XSLT 转换 XML

问题描述

我一直在尝试使用 XSLT 转换 XML 文件,但由于一些问题,即“xmlns:ns0”和 ns0:catalog,它没有转换。请帮我解决。

XML:

<?xml version="1.0" encoding="UTF-8"?>
<ns0:catalog xmlns:ns0="http://sap.com">
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <country>UK</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1988</year>
  </cd>
</ns0:catalog>

XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="/">
        <MyCatalog>
            <xsl:for-each select="catalog/cd">
                <cd>
                    <title>
                        <xsl:value-of select="title" />
                    </title>
                </cd>
            </xsl:for-each>
        </MyCatalog>
    </xsl:template>
</xsl:stylesheet>

预期成绩:

<?xml version="1.0" encoding="UTF-8"?>
<MyCatalog>
    <cd>
        <title>Empire Burlesque</title>
    </cd>
    <cd>
        <title>Hide your heart</title>
    </cd>
</MyCatalog>

标签: xmlxslt

解决方案


您需要将命名空间添加到您的选择器:

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:ns0="http://sap.com">

    <xsl:template match="/">
        <MyCatalog>
            <xsl:for-each select="ns0:catalog/cd">
                <cd>
                    <title>
                        <xsl:value-of select="title" />
                    </title>
                </cd>
            </xsl:for-each>
        </MyCatalog>
    </xsl:template>
</xsl:stylesheet>

推荐阅读