使用xslt将同一父级的兄弟姐妹分成不同的父级

时间:2016-08-18 05:27:02

标签: xml xslt

将同一父母的兄弟姐妹分成同一祖先的不同父母。

输入xml:

<surname>Nielsen</surname>

<given-name>M A</given-name>

<surname>Chuang</surname>

<given-name>I L</given-name>

输出xml我想要如下:

<name>

    <surname>Nielsen</surname>

    <given-names>M A</given-names>

</name>

<name>

    <surname>Chuang</surname>

    <given-names>I L</given-names>

</name>

2 个答案:

答案 0 :(得分:1)

试试这个(XSLT1.0)

XML:

<root>
    <surname>Nielsen</surname>
    <given-name>M A</given-name>
    <surname>Chuang</surname>
    <given-name>I L</given-name>
</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" />
      <xsl:template match="/root">
            <xsl:copy>
                <xsl:for-each select="surname">
                    <name>
                        <xsl:copy-of select="."/>
                        <xsl:copy-of select="following-sibling::given-name[1]"/>
                    </name>
                </xsl:for-each>
            </xsl:copy>
      </xsl:template>
    </xsl:stylesheet>

输出:

<?xml version="1.0"?>
<root>
  <name>
    <surname>Nielsen</surname>
    <given-name>M A</given-name>
  </name>
  <name>
    <surname>Chuang</surname>
    <given-name>I L</given-name>
  </name>
</root>

答案 1 :(得分:0)

试试这个(XSLT2)

<强> XML:

<root>
<surname>Nielsen</surname>
<given-name>M A</given-name>

<surname>Chuang</surname>
<given-name>I L</given-name>
</root>

XSLT 2.0:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes" />

<xsl:template match="root">
    <xsl:copy>
    <xsl:for-each-group select="*" group-starting-with="surname">
        <name>
            <xsl:copy-of select="current-group()" />
        </name>
    </xsl:for-each-group>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

<强>输出:

<root>
  <name>
   <surname>Nielsen</surname>
   <given-name>M A</given-name>
  </name>
  <name>
   <surname>Chuang</surname>
   <given-name>I L</given-name>
  </name>
</root>