1

我正在尝试生成 XML 输出,并且我已经创建了一个 XSLT 来执行此操作。但是,根节点缺少一些名称间距。如何将命名空间添加到 XML 结构的根元素。这是我正在使用的 XSLT:

XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
    xmlns:doc="urn:sapcom:document:sap:rfc:functions" xmlns:r="http://www.castiron.com/response" exclude-result-prefixes="r">
    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/">
        <xsl:element name="imageScene7Request">
            <xsl:element name="productIds">
                <xsl:for-each select="r:productGetAllByIdsResponse/r:payload/r:products">
                    <xsl:value-of select="r:id"/>
                    <xsl:if test="position() != last()">
                        <xsl:text>,</xsl:text>
                    </xsl:if>
                </xsl:for-each>
            </xsl:element>
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>

我想添加到根目录的命名空间http://www.castiron.com/response

输入 XML

<?xml version="1.0" encoding="UTF-8"?>
<productGetAllByIdsResponse xmlns="http://www.castiron.com/response">
    <rcode>0</rcode>
    <rmessage>Success</rmessage>
    <payload>
        <products>
            <id>4022280</id>
        </products>
        <products>
            <id>4022280</id>
        </products>
    </payload>
</productGetAllByIdsResponse>

您会看到,当您运行时,它会为您提供:

<?xml version="1.0" encoding="utf-8"?>
<imageScene7Request>
    <productIds>4022280,4022280</productIds>
</imageScene7Request>

但是我想要这个:

<?xml version="1.0" encoding="utf-8"?>
<imageScene7Request xmlns="http://www.castiron.com/response">
    <productIds>4022280,4022280</productIds>
</imageScene7Request>

回复@dbaseman

这很有效,但是它随后为第二个标签提供了一个空命名空间,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<imageScene7Request xmlns="http://www.castiron.com/response">
    <productIds xmlns="">4022280,4022280</productIds>
</imageScene7Request>

有没有办法消除它?

4

3 回答 3

3

由于您静态地知道结果元素的名称是什么,因此最好使用文字结果元素而不是 xsl:element:

 <xsl:template match="/">
    <imageScene7Request xmlns="http://www.castiron.com/response">
        <productIds>
            <xsl:for-each select="r:productGetAllByIdsResponse/r:payload/r:products">
                <xsl:value-of select="r:id"/>
                <xsl:if test="position() != last()">
                    <xsl:text>,</xsl:text>
                </xsl:if>
            </xsl:for-each>
        </productIds>
    </imageScene7Request>
</xsl:template>

如果确实使用 xsl:element,则需要确保使用命名空间属性来确保元素位于正确的命名空间中。

于 2012-05-30T13:10:46.273 回答
2

我认为您只需要在样式表中明确指定命名空间:

<xsl:element name="imageScene7Request" namespace="http://www.castiron.com/response">
    <xsl:element name="productIds">
       ...
    </xsl:element>
</xsl:element>
于 2012-05-30T09:10:17.903 回答
1

这行得通吗?

<xsl:stylesheet xmlns="http://www.castiron.com/response" ...>

这会将 XSLT 中所有元素的命名空间设置为http://www.castiron.com/response

于 2012-05-30T13:24:39.810 回答