Xslt 组父/子 [英] Xslt group parent/child

查看:50
本文介绍了Xslt 组父/子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从 xml/xslt 转换中获得以下结果:

I have a trouble getting the following result from a xml/xslt transformation:

<root>
  <node>   
    <id>1</id>
    <parentid></parentid>
    <name>file 1</name>
  <node>
  <node>   
    <id>2</id>
    <parentid></parentid>
    <name>file 2</name>
  <node>
  <node>   
    <id>3</id>
    <parentid>2</parentid>
    <name>file 3</name>
  <node>
  <node>   
    <id>4</id>
    <parentid></parentid>
    <name>file 4</name>
  <node>
  <node>   
    <id>5</id>
    <parentid>2</parentid>
    <name>file 5</name>
  <node>
</root>

我希望输出的 html 类似于:

i would like the output html to be something like:

 <ul>
    <li>file 1</li>
    <li>file 2</li>
       <ul>
          <li>file 3</li>
          <li>file 5</li>
       </ul>
    <li>file 4</li>
 </ul>

推荐答案

<?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:strip-space elements="*"/>

    <xsl:template match="/root">
        <ul>
            <xsl:apply-templates select="node[string-length(parentid)=0]" />
        </ul>
    </xsl:template>

    <xsl:template match="node">
        <li>
            <xsl:value-of select="name"/>
        </li>
        <xsl:variable name="children" select="parent::*/node[parentid=current()/id]" />
        <xsl:if test="$children">
            <ul>
                <xsl:apply-templates select="$children" />
            </ul>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

这篇关于Xslt 组父/子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆