【问题标题】:How to replace an XML attribute using XSLT when a certain other attribute is filled?填充某个其他属性时如何使用 XSLT 替换 XML 属性?
【发布时间】:2017-08-22 10:50:30
【问题描述】:

我有两个可能的 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>

我希望将&lt;code&gt;tag 的value 属性替换为&lt;altCode&gt;tag 的value 属性,除非第二个值为空。在那种情况下,我希望 XML te 保持不变。 &lt;altCode&gt;tag 不需要更改。

所以生成的两个 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 语句之后更改属性。

非常感谢任何帮助。

【问题讨论】:

  • "我更喜欢复制模板并在使用 when 语句后更改属性。" 什么模板?你没有显示为任何模板,我们不知道它匹配什么,这很关键。

标签: xml xslt-1.0


【解决方案1】:

我建议你这样做:

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>

【讨论】:

  • 谢谢迈克尔!就是这样。我得到了大部分,但卡在了最后一部分。你能解释一下那部分吗? &lt;xsl:template match="code/@value[string(../../altCode/@value)]"&gt; &lt;xsl:copy-of select="../../altCode/@value"/&gt; &lt;/xsl:template&gt; 我知道 @-part,但我不知道 '[ ]'、string 和 '../'。几天前刚开始使用 XSLT。
  • @ChananIppel 第二个模板匹配codevalue 属性在[谓词] 部分中表达的条件。当兄弟的altCode/@value 不是空字符串时,谓词的计算结果为真。否则,该属性将被第一个模板原样复制。 ../ 表示升到父级。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-09
  • 1970-01-01
  • 1970-01-01
  • 2013-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多