请教xsl高手:线性xml如何转嵌套xml

yjs_lh 2003-09-24 07:15:50
有一线性xml文档,结构如下:
<Root>
<Child>
<treeid>1</treeid>
<name>aaa</name>
<parentid>0</parentid>
</Child>
<Child>
<treeid>2</treeid>
<name>aaa</name>
<parentid>1</parentid>
</Child>
<Child>
<treeid>3</treeid>
<name>aaa</name>
<parentid>0</parentid>
</Child>
...
</Root>
现欲通过xsl将它转化为嵌套的节点,如:
<Root>
<Child>
<treeid>1</treeid>
<name>aaa</name>
<parentid>0</parentid>
<Childs>
<Child>
<treeid>2</treeid>
<name>aaa</name>
<parentid>1</parentid>
<Childs>
<Child>
<treeid>3</treeid>
<name>aaa</name>
<parentid>0</parentid>
<Childs/>
</Child>
</Childs>
</Child>
<Childs>
<Child>
...
<Root>
应该如何做?
我觉得问题的关键在于如何在select("//Child[parentid=?]")的?处如何加入本节点的属性值。但很显示select("//Child[parentid=child::treeid]")是错误的。
...全文
33 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
月光易水 2003-09-25
  • 打赏
  • 举报
回复

:_)
yjs_lh 2003-09-24
  • 打赏
  • 举报
回复
多谢多谢,问题已解决,准备给分。
也罢,暂且保留一段时间,让大家都学习学习。
月光易水 2003-09-24
  • 打赏
  • 举报
回复
树型结构,可以递归调用模板实现数据转换

try:
<?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" version="1.0" encoding="utf-8" indent="yes" />

<xsl:template match="/">
<xsl:call-template name="Childs">
<xsl:with-param name="parentid">0</xsl:with-param>
</xsl:call-template>
</xsl:template>

<xsl:template name="Childs">
<xsl:param name="parentid" />
<xsl:choose>
<xsl:when test="$parentid = 0">
<Root>
<xsl:call-template name="Child">
<xsl:with-param name="parentid" select="$parentid" />
</xsl:call-template>
</Root>
</xsl:when>
<xsl:otherwise>
<Childs>
<xsl:call-template name="Child">
<xsl:with-param name="parentid" select="$parentid" />
</xsl:call-template>
</Childs>
</xsl:otherwise>
</xsl:choose>
</xsl:template>

<xsl:template name="Child">
<xsl:param name="parentid" />
<xsl:for-each select="/Root/Child[parentid = $parentid]">
<xsl:variable name="treeid"><xsl:value-of select="treeid" /></xsl:variable>
<Child>

<!-- 获得 当前Child节点数据 -->
<xsl:for-each select="*">
<xsl:copy-of select="." />
</xsl:for-each>

<!-- 获得 丛属于当前Child节点的子节点数据(形成递归调用) -->
<xsl:if test="count(/Root/Child[parentid = $treeid]) > 0">
<xsl:call-template name="Childs">
<xsl:with-param name="parentid" select="$treeid" />
</xsl:call-template>
</xsl:if>
</Child>
</xsl:for-each>
</xsl:template>

</xsl:stylesheet>



:_)
yjs_lh 2003-09-24
  • 打赏
  • 举报
回复
笔误,treeid = 3那个节点的parentid写错,特此更正。
<Child>
<treeid>3</treeid>
<name>aaa</name>
<parentid>2</parentid>
</Child>

8,906

社区成员

发帖
与我相关
我的任务
社区描述
XML/XSL相关问题讨论专区
社区管理员
  • XML/XSL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧