xml - 简单的 XSLT 属性添加

标签 xml xslt xpath

我想在我的 XML 文档上做一些非常简单的 XSLT,它的结构如下:

<XML>
    <TAG1 attribute1="A">
        <IRRELEVANT />
        <TAG2 attribute2="B" attribute3="34" />
    </TAG1>
</XML>

我正在尝试制作一个执行以下操作的 XSLT:

  1. 复制所有内容
  2. 如果 TAG2@attribute1="A"AND TAG2@attribute2="B"并且没有 TAG2@attribute4,则将 @attribute4 添加到 TAG2 并使其值为 TAG2@attribute3 的值

我不成功的尝试如下。我得到的错误是 “xsl:attribute:如果已将子项添加到元素,则无法向该元素添加属性。”

谢谢!

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"  
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:param name="newDocumentHeader" />

   <!-- copy idiom copying ALL nodes -->
   <xsl:template match="node()|@*">
      <xsl:copy>
         <xsl:apply-templates select="node() | @*" />
      </xsl:copy>
   </xsl:template>

   <!-- override for special case -->
   <xsl:template match="TAG1[@attribute1='A']/TAG2[@attribute2='B'][not(@attribute4)]">
        <xsl:attribute name="attribute4">
        <xsl:value-of select="@attribute3" />
        </xsl:attribute>
    </xsl:template>

</xsl:stylesheet>

最佳答案

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="node() | @*">
        <xsl:copy>
            <xsl:apply-templates select="node() | @*" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="TAG1[@attribute1 = 'A']/TAG2[@attribute2= 'B' ][not(@attribute4)]">
        <xsl:copy>
            <xsl:attribute name="attribute4">
                <xsl:value-of select="@attribute3" />
            </xsl:attribute>
            <xsl:apply-templates  select="node() | @*"/>
        </xsl:copy>

    </xsl:template>

</xsl:stylesheet>

结果:

<XML>
    <TAG1 attribute1="A">
        <IRRELEVANT />
        <TAG2 attribute4="34" attribute2="B" attribute3="34" />
    </TAG1>
</XML>

关于xml - 简单的 XSLT 属性添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6815512/

相关文章:

python - 如何根据 HTML 通过 Selenium 和 Python 将文本发送到文本区域

java - 如何在 Android Studio 中更改提示文本颜色?

asp.net - WCF 返回 xml 而不是 JSON

xml - 如何通过 XPath 访问具有多个命名空间的 XML 中的元素?

python - XPath - 在单个查询中选择特定节点的前后兄弟节点

Python 通过 xml 抓取打印空括号

java - 类NamePool使用大量Java堆

php - 有没有办法通过节点名称获取简单的 XML 子元素?

xml - XSLT 能做 CSS 能做的一切吗?

html - xsltproc html 文档