通过XML树迭代并使用XSL查找公共节点文本

时间:2015-08-03 19:42:12

标签: xml xslt

我想迭代一棵树,找到共同的元素文本,并能够在表格中显示。

<Root>    
 <attr>
    <attrlabl>Attribute Label 1</attrlabl>
    <attrdef>Attribute Definition 1</attrdef>
    <attrdomv>
        <edom>
            <edomv>O</edomv>
            <edomd>Open</edomd>
        </edom>
        <edom>
            <edomv>C</edomv>
            <edomd>Close</edomd>
        </edom>
    </attrdomv>
 </attr>
 <attr>
    <attrlabl>Attribute Label 2</attrlabl>
    <attrdef>Attribute Definition 2</attrdef>
    <attrdomv>
        <edom>
            <edomv>O</edomv>
            <edomd>Open</edomd>
        </edom>
        <edom>
            <edomv>C</edomv>
            <edomd>Close</edomd>
        </edom>
    </attrdomv>
 </attr>
 <attr>
    <attrlabl>Attribute Label 3</attrlabl>
    <attrdef>Attribute Definition 3</attrdef>
    <attrdomv>
        <udom>
            <udomv>No display</udomv>
        </udom>
    </attrdomv>
 </attr>
 <attr>
    <attrlabl>Attribute Label 4</attrlabl>
    <attrdef>Attribute Definition 4</attrdef>
    <attrdomv>
        <edom>
            <edomv>D</edomv>
            <edomd>Different</edomd>
        </edom>
    </attrdomv>
 </attr>
</Root>

输出应该类似于这样,其中只显示公共元素文本。任何帮助将不胜感激!

<tr>
<td> For Attribute Label 1 and 2</td>
</tr>
<tr>
<td> Value: O </td>
<td> Description: Open </td>
</tr>
<tr>
<td> Value: C </td>
<td> Description: Close </td>

1 个答案:

答案 0 :(得分:1)

尝试以下几点:

XSLT 2.0

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

<xsl:template match="/Root">
    <table border="1">
        <xsl:for-each-group select="attr/attrdomv/edom" group-by="edomv">
            <xsl:if test="count(current-group()) > 1">
                <tr>
                    <td>
                        <xsl:value-of select="current-group()/ancestor::attr/attrlabl" separator=", "/>
                    </td>
                    <td>
                        <xsl:text>Value: </xsl:text>
                        <xsl:value-of select="current-grouping-key()"/>
                    </td>
                    <td>
                        <xsl:text>Description: </xsl:text>
                        <xsl:value-of select="current-group()[1]/edomd"/>
                    </td>
                </tr>
            </xsl:if>
        </xsl:for-each-group>
    </table>
</xsl:template>

</xsl:stylesheet>

结果应用于您的示例输入时,与您的结果略有不同:

<table border="1">
   <tr>
      <td>Attribute Label 1, Attribute Label 2</td>
      <td>Value: O</td>
      <td>Description: Open</td>
   </tr>
   <tr>
      <td>Attribute Label 1, Attribute Label 2</td>
      <td>Value: C</td>
      <td>Description: Close</td>
   </tr>
</table>

主要是因为我认为祖先的身份不过是巧合。