列出元素 XSLT 的子节点

Enz*_*ero 5 xml xslt xslt-2.0

所以我想列出具有 Specs 节点名称和文本的所有子节点。

<Item-Request model="MZ-7TE1T0BW" Supplier-Code="TOMSAM1TB">
    <DisplayItem>
        <Item href="SAM1TBMZ7TE1T0BW.jpg" model="MZ-7TE1T0BW">
            <Name>Samsung SSD MZ-7TE1T0BW 1 TB 2.5 inch</Name>
            <Price>630.99</Price>
            <SupplierCode>TOMSAM1TB</SupplierCode>
            <Description/>
            <Specs>
                <Capacity>1 TB</Capacity>
                <Reading>540 MB/s</Reading>
                <Writing>520 MB/s</Writing>
                <FormFactor>2.5 "</FormFactor>
                <Connecor>Sata III</Connecor>
                <Size>
                    <Width>70 mm</Width>
                    <Height>7 mm</Height>
                </Size>
                <Weight>53 g</Weight>
            </Specs>
            <Supplier>TOM001</Supplier>
            <SupplierName>Tom PC Hardware</SupplierName>
            <Manufacturer>Samsung</Manufacturer>
        </Item>
    </DisplayItem>
</Item-Request>
Run Code Online (Sandbox Code Playgroud)

我无法执行此硬编码,因为这些值不是我随时可用且可以添加或删除的值。所以我需要一些可以动态列出它们的东西。

到目前为止我能做的是

<xsl:for-each select="DisplayItem/Item/Specs">
                                <xsl:for-each select="node()">
                                    <xsl:value-of select="."/>
                                    <br/>
                                </xsl:for-each>
                            </xsl:for-each>
Run Code Online (Sandbox Code Playgroud)

上面在单独的行上列出了值,现在我需要能够显示元素名称。

mwi*_*.me 2

您不应该循环遍历所有子元素,而应该使用找到的 Specs 元素的模板,并将每个元素转换为文本。

我将使用以下样式表(看来您想生成 HTML):

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns="http://www.w3.org/1999/xhtml" 
                              xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" indent="yes"/>  

  <xsl:template match="/">
    <xsl:text disable-output-escaping='yes'>&lt;!DOCTYPE html></xsl:text>
      <html>
      <body>
        <xsl:apply-templates/>
      </body>
      </html>
  </xsl:template>

  <xsl:template match="Specs">
      <xsl:for-each select="*"> <!-- take all descendants of Specs -->
        <p>
          <xsl:value-of select="name()"/>
          <xsl:text> = </xsl:text>

          <!-- this just copies the text() of possible descendants! -->
          <xsl:value-of select="."/> 
        </p>
      </xsl:for-each>
  </xsl:template>

  <!-- do nothing for unmatched text or attribute nodes -->
  <xsl:template match="text()|@*"/>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

您仍然会遇到嵌套规范的问题,<Size>例如。使用此模板,输出为(减去一些额外的空格):

<p>Size = 70 mm 7 mm</p>
Run Code Online (Sandbox Code Playgroud)