我正在尝试使用XSL对XML元素进行排序,类似于这篇文章: How to sort some XML elements according to their dependencies, by using XSLT?,但就我而言,我有以下xml:
<root>
<element name="a" predecessor="x">
<children>
<element name="b" predecessor="c"/>
<element name="c" predecessor="a"/>
<element name="d" predecessor="b"/>
</children>
</element>
</root>
预期输出为:
<root>
<element name="a" predecessor="x">
<children>
<element name="c" predecessor="a"/>
<element name="b" predecessor="c"/>
<element name="d" predecessor="b"/>
</children>
</element>
</root>
你能帮助我实现这个目标吗?
答案 0 :(得分:0)
您可以尝试使用这种递归方法:
<?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="@* | *">
<xsl:copy>
<xsl:apply-templates select="@* | node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="/">
<xsl:apply-templates select="@* | node()" />
</xsl:template>
<xsl:template match="children" >
<xsl:copy>
<xsl:apply-templates select="element[@predecessor=current()/../@name]"/>
</xsl:copy>
</xsl:template>
<xsl:template match="element">
<xsl:copy>
<xsl:apply-templates select="@* | node()" />
</xsl:copy>
<xsl:apply-templates select="../element[@predecessor=current()/@name]" />
</xsl:template>
</xsl:stylesheet>
将生成以下输出:
<?xml version="1.0"?>
<root>
<element name="a" predecessor="x">
<children>
<element name="c" predecessor="a"/>
<element name="b" predecessor="c"/>
<element name="d" predecessor="b"/>
</children>
</element>
</root>