利用XSLT将线性XML转换为树型XML

对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>


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>

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值