2017-06-20 87 views
0

我有一个有关获取每个元素的子元素在具有相同名称的节点列表中的问题(以下示例中的“b”元素)。XSLT在具有多个具有相同名称的节点时进行转换

我在Google搜索(并搜索此网站)的尝试没有取得任何结果。

我的实际XML比较冗长,但是我做了一个简化版本来重现结果。它看起来像这样:

<?xml version="1.0" encoding="UTF-8"?> 
<a> 
    <b> 
    <c> 
     <d>Value 1</d> 
    </c> 
    </b> 
    <b> 
    <c> 
     <d>Value 2</d> 
    </c> 
    </b> 
    <b> 
    <c> 
     <d>Value 3</d> 
    </c> 
    </b> 
</a> 

我希望将其转变为一个结构是这样的:

<?xml version="1.0" encoding="UTF-8"?> 
<docRoot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="our.urn.namespace our.xsd"> 
    <subEl> 
     <value>Value 1</value> 
    </subEl> 
    <subEl> 
     <value>Value 2</value> 
    </subEl> 
    <subEl> 
     <value>Value 3</value> 
    </subEl> 
</docRoot> 

我的XSLT是这样的:

<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" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <xsl:output method="xml" indent="yes"/> 

    <xsl:template match="https://stackoverflow.com/a/b/c/d/text()"> 
    <xsl:element name="value"> 
     <xsl:value-of select="https://stackoverflow.com/a/b/c/d"/> 
    </xsl:element> 
    </xsl:template> 

    <xsl:template match="https://stackoverflow.com/a/b/c"> 
    <xsl:element name="subEl"> 
     <xsl:apply-templates select="./d/text()"/> 
    </xsl:element> 
    </xsl:template> 

    <xsl:template match="/"> 
    <xsl:element name="docRoot"> 
     <xsl:attribute name="xsi:schemaLocation">our.urn.namespace our.xsd</xsl:attribute> 
     <xsl:apply-templates select="https://stackoverflow.com/a/b/c"/> 
    </xsl:element> 
    </xsl:template> 
</xsl:stylesheet> 

然而,这提供了以下结果:

<?xml version="1.0" encoding="UTF-8"?> 
<docRoot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="our.urn.namespace our.xsd"> 
    <subEl> 
     <value>Value 1</value> 
    </subEl> 
    <subEl> 
     <value>Value 1</value> 
    </subEl> 
    <subEl> 
     <value>Value 1</value> 
    </subEl> 
</docRoot> 

很明显我没有正确选择。有谁知道适当的xpath来获得所需的输出?

注:我也做出了尝试,其中模板匹配“/”有

<xsl:apply-templates select="https://stackoverflow.com/a/b"/> 

,而不是在上面的例子中是什么,然后我用了,每次在它应用的模板,但没有改变在结果中。在我看来,这表示问题出在xpath上。 另外我宁愿不要为了可维护性而使用for-each。

回答

0

尝试合并的前两个模板匹配到:

<xsl:template match="https://stackoverflow.com/a/b/c"> 
    <xsl:element name="subEl"> 
    <xsl:element name="value"> 
     <xsl:value-of select="./d/text()"/> 
    </xsl:element> 
    </xsl:element> 
</xsl:template> 

编辑:如果你想要的东西更接近你的方法,你可以做

<xsl:template match="https://stackoverflow.com/a/b/c/d"> 
    <xsl:element name="value"> 
     <xsl:value-of select="text()"/> 
    </xsl:element> 
    </xsl:template> 

    <xsl:template match="https://stackoverflow.com/a/b/c"> 
    <xsl:element name="subEl"> 
     <xsl:apply-templates select="./d"/> 
    </xsl:element> 
    </xsl:template> 
+0

谢谢。那就是诀窍。 – LordPilum

相关问题