将XML展平为HTML表格

6 xml xslt xpath

必须有一种通用的方法来转换某些层次XML,例如:

<element1 A="AValue" B="BValue">
   <element2 C="DValue" D="CValue">
      <element3 E="EValue1" F="FValue1"/>
      <element3 E="EValue2" F="FValue2"/>
   </element2>
   ...
</element1>
Run Code Online (Sandbox Code Playgroud)

进入扁平化的XML(html),沿途拾取所选属性,并为成为列标题的属性提供不同的标签.

<table>
   <tr>
     <th>A_Label</th>
     <th>D_Label</th>
     <th>E_Label</th>
     <th>F_Label</th>
   </tr>
   <tr>
     <td>AValue</td>
     <td>DValue</td>
     <td>EValue1</td>
     <td>FValue1</td>
   </tr>
   <tr>
     <td>AValue</td>
     <td>DValue</td>
     <td>EValue2</td>
     <td>FValue2</td>
   </tr>
<table>
Run Code Online (Sandbox Code Playgroud)

好的,所以由于属性重新标记,没有通用的解决方案,但你明白了我的意思.我刚刚开始使用所有的XSLT/XPATH,所以我会在适当的时候解决它,但任何线索都会有用.

Dar*_*ler 5

我不是100%确定你要做什么,但是如果你的element1,element2和element3是一致的嵌套,这个解决方案可能会有效.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="/">
        <table>
            <xsl:apply-templates select="//element3"></xsl:apply-templates>
        </table>
    </xsl:template>

    <xsl:template match="element3">
        <tr>
            <td><xsl:value-of select="../../@A"/></td>
            <td><xsl:value-of select="../../@B"/></td>
            <td><xsl:value-of select="../@C"/></td>
            <td><xsl:value-of select="../@D"/></td>
            <td><xsl:value-of select="@E"/></td>
            <td><xsl:value-of select="@F"/></td>
        </tr>
        <xsl:apply-templates select="*"></xsl:apply-templates>
    </xsl:template>

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