3

我有以下输入 XML:

<root>
    <aaa>some string aaa</aaa>
    <bbb>some string bbb</bbb>
    <ddd>some string ddd</ddd> 
</root>

使用 XSLT 我想要以下输出:

<root>
    <aaa>some string aaa</aaa>
    <bbb>some string bbb</bbb>
    <ccc>some string ccc</ccc>
    <ddd>some string ddd</ddd>
</root>

我的 XSLT 是:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.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="root">
        <root>
            <ccc>some string ccc</ccc>
            <xsl:apply-templates select="@*|node()"/> 
        </root>
    </xsl:template>
</xsl:stylesheet>

但我没有得到我想要的输出。如何使用标识模板将元素放在和ccc元素之间?bbbddd

如果有帮助,我可以使用 XSLT 3.0。

4

2 回答 2

3

Kenneth 的回答很好,但由于问题被标记为 XSLT 3.0,它可以写得更紧凑,所以我添加了这个答案作为替代

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

    <xsl:output indent="yes"/>

    <xsl:mode on-no-match="shallow-copy"/>

    <xsl:template match="ddd">
        <ccc>some string ccc</ccc>
        <xsl:next-match/>
    </xsl:template>

</xsl:stylesheet>

using<xsl:mode on-no-match="shallow-copy"/>表示身份转换,并 using将元素的<xsl:next-match/>复制委托给它。ddd

于 2017-10-07T07:14:37.197 回答
3

使用与插入点之前或之后的元素匹配的第二个模板进行恒等转换,然后在复制匹配的元素之后或之前插入新元素。以机智:

给定这个输入 XML,

<root>
   <aaa>some string aaa</aaa>
   <bbb>some string bbb</bbb>
   <ddd>some string ddd</ddd> 
</root>

这个 XSLT,

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

  <xsl:output method="xml" indent="yes"/>

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

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

</xsl:stylesheet>

将生成此输出 XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <aaa>some string aaa</aaa>
   <bbb>some string bbb</bbb>
   <ccc>some string ccc</ccc>
   <ddd>some string ddd</ddd> 
</root>
于 2017-10-06T23:04:04.353 回答