当填充某个其他属性时,如何使用 XSLT 替换 XML 属性?



我得到了两个可能的XML文件:

<orders>
<order id="1">
<code value="001-AAA"/>
<altCode value="002-BBB"/>
</order>
</orders>

和:

<orders>
<order id="2">
<code value="001-AAA"/>
<altCode value=""/>
</order>
</orders>

我希望将<code>标签的value属性替换为<altCode>标签的value属性,除非第二个值为空。在这种情况下,我希望 XML te 保持不变。<altCode>标记不需要更改。

因此,生成的两个 XML 文件应如下所示:

<orders>
<order id="1">
<code value="002-BBB"/>
<altCode value="002-BBB"/>
</order>
</orders>

和:

<orders>
<order id="2">
<code value="001-AAA"/>
<altCode value=""/>
</order>
</orders>

注意:我喜欢转换的实际文件要复杂得多。所以我更喜欢复制模板并在使用 when-语句之后更改属性。

任何帮助都非常感谢。

我建议你这样做:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="code/@value[string(../../altCode/@value)]">
<xsl:copy-of select="../../altCode/@value"/>
</xsl:template>
</xsl:stylesheet>

最新更新