我正在尝试生成一个 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>
有没有办法去除它?
最佳答案
因为您静态地知道结果元素的名称是什么,所以最好使用文字结果元素而不是 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,则需要确保使用命名空间属性以确保该元素位于正确的命名空间中。
关于xml - XSLT - 将 namespace 添加到输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10812901/