【问题标题】:Parse arbitrarily deep xml using xsl使用 xsl 解析任意深度的 xml
【发布时间】:2013-11-14 22:43:13
【问题描述】:

我正在尝试使用 XSL 文件解析 XML 文件。

我的问题是,我的 XML 文件可以包含任意深度的路径 f.x。

<document>
    <branch>
        <data>somedata</data>
        <children>
            <branch>
                <data>somedata</data>
                <children>
                    ....
                </children>
            </branch>
         </children>
     </branch>
</document>

我不知道这些节点的深度,但我知道它们是如何命名的。如何提取每个节点 f.x. 的内容?

我想保留节点的层次结构。

谢谢。

我找到了解决方案。不知道这是否是 Martin og HashCoder 的意思:

<xsl:template match="branch">
    <p><xsl:value-of select="branchcontent.list/branchtext/properties.list/p/@v"/></p>
        <xsl:apply-templates select="subbranches.list"/>
</xsl:template>

【问题讨论】:

    标签: xml xslt xml-parsing


    【解决方案1】:

    您的问题对我来说不是很清楚..您是否要复制所有节点值?

    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
            <xsl:output indent="yes"/>
            <xsl:strip-space elements="*"/>
        <xsl:template match="@* | node()">
          <xsl:copy>
            <xsl:apply-templates select="@* , node()"/>
          </xsl:copy>
        </xsl:template>
    </xsl:stylesheet>
    

    【讨论】:

    • 我正在尝试提取数据元素的值,然后将其解析为 html,在其中将层次结构保存在项目符号列表中。
    【解决方案2】:

    如果你想扁平化层次结构使用

    <xsl:template match="/">
      <xsl:apply-templates select="//data"/>
    </xsl:template>
    
    <xsl:template match="data">
      <xsl:value-of select="."/>
    </xsl:template>
    

    如果要遍历并保留层次结构,请使用

    <xsl:template match="branch">
      <div>
       <xsl:apply-templates/>
      </div>
    </xsl:template>
    
        <xsl:template match="data">
          <xsl:value-of select="."/>
        </xsl:template>
    

    【讨论】:

    • 关于最底层的答案:对于xml文件中的每个分支元素,你返回data标签的内容?代码应该这样读吗?
    • 您还没有解释您想要哪种类型的结果(XML、HTML、纯文本)。假设 HTML,第二种方法为任何 branch 元素创建 HTML div 结果元素,并使用匹配模板处理子节点,这些模板是 data 元素的模板,为其他元素创建文本节点和内置模板跟上递归。
    猜你喜欢
    • 2023-03-18
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 2023-03-06
    • 2011-06-13
    相关资源
    最近更新 更多