使用 xsl 列出 xml 文档元素的(直接!)子元素

List the (direct!) children of the elements of an xml-document using xsl

我正在尝试使用 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>

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

提前感谢您的回答!

假设您想要一个简单的列表格式,这只是修改您的示例 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>