【问题标题】:List the (direct!) children of the elements of an xml-document using xsl使用 xsl 列出 xml 文档元素的(直接!)子元素
【发布时间】:2018-01-15 01:18:23
【问题描述】:

我正在尝试使用 xsl 分析复杂的 xml 文件。

我设法用这段代码列出了所有元素及其各自的父元素:

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

   <xsl:template match = "/"> 
  <xsl:for-each select="//element()">
        <xsl:value-of select="name()"/><xsl:text>; </xsl:text>
        <xsl:value-of select="name(..)"/><xsl:text>; </xsl:text>
        <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
   </xsl:template>  
</xsl:stylesheet>

如何也列出每个元素的(直接!)子元素?

提前感谢您的回答!

【问题讨论】:

  • 您要列出什么,子元素的名称,子元素或节点的值一般?你想要什么格式?
  • 如果您知道如何使用 XPath 选择元素,那么您应该不会很难找到如何选择子元素,规范中包含所有详细信息 w3.org/TR/xpath/#path-abbrev

标签: xml xslt children


【解决方案1】:

假设您想要一个简单的列表格式,这只是修改您的示例 XSL 代码以添加直接子名称的输出。

<xsl:template match="/">
    <xsl:for-each select="//element()">
        <xsl:value-of select="name()"/>
        <xsl:text>; </xsl:text>
        <xsl:value-of select="name(..)"/>
        <!-- Direct children:
        The `*` here in the `select` statement just selects 
        all child elements.  This could also be expressed
        (perhaps more clearly, but also more verbosely) as
        either of the following:
            ./*
            child::*
        -->
        <xsl:for-each select="*">
            <!-- We put the semicolon before each child's name.
                That way, if there are no children, we don't have
                an extraneous semicolon after the parent's name.-->
            <xsl:text>; </xsl:text>
            <xsl:value-of select="name()"/>
        </xsl:for-each>
        <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
</xsl:template>

【讨论】:

    猜你喜欢
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    相关资源
    最近更新 更多