使用 XSLT 转换展平嵌套的 XML/层次结构 [英] Flatten Nested XML/hierarchy using XSLT Transformation

查看:29
本文介绍了使用 XSLT 转换展平嵌套的 XML/层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的分层 xml 结构,它将使用 xsl 转换进行展平.以下是场景.

I have a nested hierarchial xml structure which is to be flattened using xsl transformation. Following is the scenario.

<company>
  <Managers>
    <Manager>
       <Name>Matt</Name>
       <ID>1</ID>
       <Manager>
          <Name>Joe</Name>
          <ID>11</ID>
          <Manager>
          <Name>Dave</Name>
          <ID>111</ID>
       </Manager>
       </Manager>
    </Manager>
    <Manager>
        <Name>mike</Name>
          <ID>2</ID>>
    </Manager>
  </Managers>
</company>

结果:

Matt 1
Joe 11
Dave 111
Mike 2

推荐答案

一个更好的选择来自@Mathias Mueller,

A better alternative via @Mathias Mueller,

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="text" encoding="UTF-8"/>

    <xsl:template match="Manager">
        <xsl:value-of select="Name" />
        <xsl:text>: </xsl:text>
        <xsl:value-of select="ID" />
        <xsl:text> </xsl:text>
        <xsl:apply-templates/>
    </xsl:template>   

    <xsl:template match="text()"/>

</xsl:transform>

为什么这样更好:它将更正确地控制文本输出(假设您确实想将其输出为纯文本格式).它也更面向 XSLT 模板,与 for-each 循环相比,它往往更具可扩展性和可维护性.

Why this is better: It will more properly control the text output (assuming you really do want to output this to plaintext format). It also is more XSLT template oriented, which tends to be more extensible and maintainable than having for-each loops hanging around.

使用 descendant-or-self 轴:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="text" doctype-public="XSLT-compat" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />

    <xsl:template match="//Managers">
       <xsl:for-each select="descendant-or-self::Manager">
        <xsl:value-of select="Name" />: <xsl:value-of select="ID" /><xsl:text> </xsl:text>
      </xsl:for-each>
    </xsl:template>    

</xsl:transform>

输出:

  Matt: 1 Joe: 11 Dave: 111 mike: 2 

http://xsltransform.net/nc4NzQB

这篇关于使用 XSLT 转换展平嵌套的 XML/层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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