对XML进行格式化控制,也是XSLT的常见应用之一。
下面代码XSLT代码将示范如何将线性XML转换为树型XML。
data.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="format.xsl"?>
<root>
<item id="1" fatherid="" name="总部"/>
<item id="2" fatherid="1" name="分公司1"/>
<item id="4" fatherid="2" name="分公司1的子公司1"/>
<item id="8" fatherid="4" name="分公司1的子公司1的子公司1"/>
<item id="7" fatherid="4" name="分公司1的子公司1的子公司2"/>
<item id="5" fatherid="7" name="分公司1的子公司1的子公司2的子公司"/>
<item id="6" fatherid="2" name="分公司1的子公司2"/>
<item id="3" fatherid="1" name="分公司2"/>
</root>
<?xml-stylesheet type="text/xsl" href="format.xsl"?>
<root>
<item id="1" fatherid="" name="总部"/>
<item id="2" fatherid="1" name="分公司1"/>
<item id="4" fatherid="2" name="分公司1的子公司1"/>
<item id="8" fatherid="4" name="分公司1的子公司1的子公司1"/>
<item id="7" fatherid="4" name="分公司1的子公司1的子公司2"/>
<item id="5" fatherid="7" name="分公司1的子公司1的子公司2的子公司"/>
<item id="6" fatherid="2" name="分公司1的子公司2"/>
<item id="3" fatherid="1" name="分公司2"/>
</root>
format.xsl:
<?xml version="1.0" encoding="gb2312"?>
<xsl:stylesheet version="1.0" xmlns:xsl=" http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/root">
<root>
<xsl:apply-templates select="*[@fatherid='']"/>
</root>
</xsl:template>
<xsl:template match="*">
<xsl:variable name="Id" select="@id"/>
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates select="/root/item[@fatherid=$Id]"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
<xsl:stylesheet version="1.0" xmlns:xsl=" http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/root">
<root>
<xsl:apply-templates select="*[@fatherid='']"/>
</root>
</xsl:template>
<xsl:template match="*">
<xsl:variable name="Id" select="@id"/>
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates select="/root/item[@fatherid=$Id]"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>