我正在尝试使用以下 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:
只需更换,
(逗号)使用|
(pipe) 在 apply-templates 中使用逗号来对操作进行排序在 2.0 中受支持:
<xsl:apply-templates select="@* | node()"/>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)