要转换的文档或多或少看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<root>
<someCatalogProp>ąć</someCatalogProp>
<meanProp>
<node id="1">
<someProperty>blabla1</someProperty>
<children>
<node idref="2"/>
</children>
</node>
<node id="2">
<someProperty>blabla2</someProperty>
<children>
<node idref="3"/>
</children>
</node>
</meanProp>
<node id="1">
<someProperty>blabla1</someProperty>
<children>
<node idref="2"/>
</children>
</node>
<node id="2">
<someProperty>blabla2</someProperty>
<children>
<node idref="3"/>
</children>
</node>
<node id="3">
<someProperty>blabla3</someProperty>
<children>
</children>
</node>
</root>
结果文档应如下所示:
<root>
<someCatalogProp>ąć</someCatalogProp>
<node id = "1">
<someProperty>blabla1</someProperty>
<children>
<node id = "2">
<someProperty>blabla2</someProperty>
<children>
<node id = "3">
<someProperty>blabla2</someProperty>
<children>
</children>
</node>
</children>
</node>
</children>
</node>
</root>
孩子的数量可以是多个。等级的深度不受限制。
转换xslt怎么样? 提前谢谢。
答案 0 :(得分:1)
使用 keys 来实现这一点非常简单。
如果您有格式正确的输入,例如:
<强> XML 强>
<root>
<node id="1">
<someProperty>blabla1</someProperty>
<children>
<node idref="2"/>
</children>
</node>
<node id="2">
<someProperty>blabla2</someProperty>
<children>
<node idref="3"/>
</children>
</node>
<node id="3">
<someProperty>blabla2</someProperty>
<children>
</children>
</node>
</root>
应用以下样式表:
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="*"/>
<xsl:key name="child" match="node" use="@id" />
<xsl:key name="parent" match="node" use="@idref" />
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/root">
<xsl:copy>
<xsl:apply-templates select="node[not(key('parent', @id))]"/>
</xsl:copy>
</xsl:template>
<xsl:template match="node[@idref]">
<xsl:apply-templates select="key('child', @idref)"/>
</xsl:template>
</xsl:stylesheet>
将产生:
<强>结果强>
<?xml version="1.0" encoding="UTF-8"?>
<root>
<node id="1">
<someProperty>blabla1</someProperty>
<children>
<node id="2">
<someProperty>blabla2</someProperty>
<children>
<node id="3">
<someProperty>blabla2</someProperty>
<children/>
</node>
</children>
</node>
</children>
</node>
</root>