2017-06-20 107 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

相關問題