我正在尝试使用以下 xsl 代码更改元素属性的命名空间:
<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:ns2="http://www.ean-ucc.org/schemas/1.3.1/eanucc">
<xsl:output encoding='UTF-8' indent='yes' method='xml'/>
<!-- copy everything into the output -->
<xsl:template match='@*|node()'>
<xsl:copy>
<xsl:apply-templates select='@*|node()'/>
</xsl:copy>
</xsl:template>
<xsl:template match="IRenvelope">
<IRL xmlns:xsd="http://www.xx.com">
<xsl:copy-of select="node()|@*"/>
</IRL>
</xsl:template>
</xsl:stylesheet>
我用于测试的 xml 消息是:
<GMessage xmlns="http://www.giffgaff.uk/CM/envelope">
<EnvelopeVersion>2.0</EnvelopeVersion>
<body>
<IRenvelope xmlns="http://www.mnv.com/elc/sap">
<Keys>
<Key Type="TaxOfficeNumber">635</Key>
</Keys>
</IRenvelope>
</body>
</GMessage>
我无法让它工作,命名空间没有改变,但提供了相同的结果。有什么帮助吗?
输出xml如下:
<GMessage xmlns="http://www.giffgaff.uk/CM/envelope">
<EnvelopeVersion>2.0</EnvelopeVersion>
<body>
<IRenvelope xmlns="http://www.xx.com">
<Keys>
<Key Type="TaxOfficeNumber">635</Key>
</Keys>
</IRenvelope>
</body>
</GMessage>
最佳答案
下面的 XSLT 将帮助您获得所需的结果:
<xsl:stylesheet
version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xsd="http://www.xx.com"
xmlns:ns="http://www.mnv.com/elc/sap"
exclude-result-prefixes="ns">
<xsl:output encoding='UTF-8' indent='yes' method='xml'/>
<!-- copy everything into the output -->
<xsl:template match='@*|node()'>
<xsl:copy>
<xsl:apply-templates select='@*, node()'/>
</xsl:copy>
</xsl:template>
<!-- template to match ns:IRenvelope element and creating a new element -->
<xsl:template match="ns:IRenvelope">
<xsl:element name="IRL" namespace="http://www.xx.com">
<xsl:apply-templates select="@*, node()"/>
</xsl:element>
</xsl:template>
<!-- template to change the namespace
of the elements
from "http://www.mnv.com/elc/sap"
to "http://www.xx.com" -->
<xsl:template match="ns:*">
<xsl:element name="{local-name()}" namespace="http://www.xx.com">
<xsl:apply-templates select="@*, node()"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
这里,最后两个模板分别匹配 ns:IRenvelope
和具有命名空间 http://www.mnv.com/elc/sap
的所有元素。使用xsl:element
及其命名空间属性,我们可以创建具有所需命名空间的新元素。
您还可以使用前缀声明所需的命名空间并创建元素,如下所示:
<xsd:IRL xmlns:xsd="http://www.xx.com">
...
</xsd:IRL>
对于 XSLT-1.0:
只需替换 ,
(逗号)即可在 apply-templates 中使用 |
(管道),就像 2.0 中支持使用逗号对操作进行排序一样:
<xsl:apply-templates select="@* | node()"/>
关于xml - XSLT 更改元素中的 namespace ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42286987/