简单的XPath映射和转换(非常基础)

时间:2014-02-17 13:22:20

标签: xml xslt xpath

问题:我在两个不同的地方拥有属性。我想在输出中只使用其中一个位置。所以我必须将(?)相应的Attribute / ID映射到ElementAttributeID。

这是我想要转换的XML:

<ID>Testdata</ID>
<Attributes>
    <Attribute>
        <ID>Time</ID>
        <Name>Time</Name>
    </Attribute>
    <Attribute>
        <ID>Place</ID>
        <Name>Place</Name>
    </Attribute>
    <Attribute>
        <ID>Sense</ID>
        <Name>Sense</Name>
    </Attribute>
</Attributes>
<Elements>
    <Element>
        <ID>First</ID>
        <Name>First</Name>
        <MGs>
            <MG>
                <Attributes>
                    <Attribute>
                        <ElementAttributeID>Time</ElementAttributeID>
                    </Attribute>
                    <Attribute>
                        <ElementAttributeID>Place</ElementAttributeID>
                    </Attribute>
                </Attributes>
            </MG>
        </MGs>
    </Element>
</Elements>

我设法编写了这个宇宙的XSL片段

    <xsl:template match="MGs/MG/Attributes/Attribute">

    <xsl:for-each select=".">
        <xsl:if test="./node() = parent::Attributes/Attribute">
            <xsl:value-of select="concat(CubeAttributeID,' Matches ',parent::Attributes/Attribute) " /> From template
        </xsl:if>
    </xsl:for-each>

</xsl:template>

转换后我发现它只映射了找到的属性,但是它不能正确映射,因为输出是:

Time Matches Time 
Place Matches Time 

因为所需的输出是:

Time Matches Time 
Place Matches Place

我是否需要一个嵌套for-each?

2 个答案:

答案 0 :(得分:0)

这是不对的..

您正在匹配模板,然后一次循环每个匹配1!删除

<xsl:for-each select="." />

它在这个上下文中基本上什么也没做,因为你选择了模板匹配的元素,所以你用循环你的上下文节点的简单术语。

另外请用您的预期输出更新您的问题,我相信我可以提供更详细的帮助!

此外,请确保您的示例x​​slt与您的示例x​​ml匹配

答案 1 :(得分:0)

在稍微阅读了xsl中的测试工作后,我做对了。 没有做映射,只有1个变量在foreach循环中使用:

             

    <xsl:template match="/">
      <html>
        <body>
        <xsl:for-each select="/Elements/Element/MGs/MG/Attributes/Attribute">
          <xsl:variable name="id" select="ElementAttributeID" />
          <div>
            <xsl:value-of select="concat(/Attributes/Attribute[ID=$id]/Name,'matches',/Elements/Element/MGs/MG/Attributes/Attribute/ElementAttributeID)"/>
          </div>
        </xsl:for-each>
        </body>
      </html>
    </xsl:template>
</xsl:stylesheet>

给出正确的结果:

Time matches Time 
Place matches Place 
相关问题