使用xslt递归解析xml [英] parsing though xml recursively using xslt

查看:65
本文介绍了使用xslt递归解析xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Xml 如下:

I have an Xml as follows:

<Soap:Envelope>
<Soap:Body>
<A>
   <B>Text</B>
   <C>Text</C>
   <D>
      <D1>Text</D1>
      <D2>
          <D3>Text</D3>
          <D4>Text</D4>
      </D2>
   </D>
   <E>
      <E1>
          <E2>
              <E3>Text</E3>
          </E2>
      </E1>
   </E>
</A>
</Soap:Body>
</Soap:Envelope>

我如何递归解析所有标签(我只知道我将收到一个 xml 模板),使用 XSLT 知道标签名称和其中的文本"?我需要以如下格式存储数据.当我没有和标签时,下面的答案工作正常.现在如何获取输出?

How do I recursively parse through all the tags(I only know that I will be receiving an xml template), know the tag names and the "Text" in them using XSLT? I need to store the data in the format as below.Below answer works fine when I don't have and tags. How to get the output now?

A_B = Text1
A_C = Text2
A_D_D1 = Text3
A_D_D2_D3 = Text4
A_D_D2_D4 = Text5
A_E_E1_E2_E3 = Text6

我知道我们需要编写一个递归函数,如下所示.这就是我需要帮助的地方.

I know that we need to write a recursive function as below. That is where I need some help.

<for-each select="./*">
   //Recursive Function
</for-each>

提前致谢

推荐答案

以下样式表:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>
<xsl:strip-space elements="*"/>

<xsl:template match="*[text()]">
    <xsl:for-each select="ancestor-or-self::*">
        <xsl:value-of select="name()" />
        <xsl:if test="position()!=last()">
            <xsl:text>_</xsl:text>
        </xsl:if>
    </xsl:for-each>
    <xsl:text> = </xsl:text>
    <xsl:value-of select="." />
    <xsl:text>&#10;</xsl:text>
    <xsl:apply-templates select="*"/>
</xsl:template>

</xsl:stylesheet>

应用于您的示例输入,将返回:

applied to your example input, will return:

A_B = Text
A_C = Text
A_D_D1 = Text
A_D_D2_D3 = Text
A_D_D2_D4 = Text
A_E_E1_E2_E3 = Text

<小时>

添加:

您的新需求定义得不够好(并且您的新 XML 格式不正确).如果我猜对了,您希望从连接路径中排除任何命名空间元素名称.如果是,请替换:


Added:

Your new requirement is not defined well enough (and your new XML is not well-formed). If I am guessing correctly, you want to exclude any namespaced element names from the concatenated path. If so, replace:

<xsl:for-each select="ancestor-or-self::*">

与:

<xsl:for-each select="ancestor-or-self::*[not(namespace-uri())]">

这篇关于使用xslt递归解析xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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