2015-12-29 170 views
1

我在循環節點時遇到問題。我有一些工作示例,但XML佈局稍有不同。通過XML元素循環的故障

XML

<FAMILY> 
<FAMILY_NAMES id="1" name="Smith"> 
    <KID name="Jim">First Born</KID> 
    <KID name="Joe">Enjoys playing outside</KID> 
    <KID name="Jon">Straight A student</KID> 
</FAMILY_NAMES> 
<FAMILY_NAMES id="2" name="Barnes"> 
    <KID name="Mike">Just got his license</KID> 
    <KID name="Dan">On vacation</KID> 
    <KID name="Ken">Going to graduate school</KID> 
</FAMILY_NAMES> 
<FAMILY_NAMES id="3" name="Thompsons"> 
<KID name="James">Loves sports</KID> 
<KID name="Ben">Middle Child</KID> 
<KID name="Frank">Youngest child</KID> 
</FAMILY_NAMES> 
</FAMILY 

我能得到家庭的名單,但我需要得到KID標籤之間的隨機信息的列表(如「喜歡打外」)下的每個家庭。到目前爲止,我只能得到一個姓氏的名單。

XSLT

<xsl:for-each select="//FAMILY/FAMILY_NAMES"> 
    <xsl:value-of select="@name"></xsl:value-of><xsl:text>&#xa;</xsl:text> 
    <xsl:for-each select="KID"> 
    <xsl:value-of select="KID"></xsl:value-of><xsl:text>&#xa;</xsl:text> 
    </xsl:for-each> 
</xsl:for-each> 

只是不知道爲什麼,這是行不通的。

回答

0

當你遍歷每個KID,當前節點已經是每個KID,所以得到KID使用<xsl:value-of select="."/>,不="KID"的字符串值。

這XSLT

<xsl:stylesheet version="1.0" 
       xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

    <xsl:output method="text" version="1.0"/> 

    <xsl:template match="/"> 
    <xsl:for-each select="/FAMILY/FAMILY_NAMES"> 
     <xsl:value-of select="@name"/> 
     <xsl:text>&#xa;</xsl:text> 
     <xsl:for-each select="KID"> 
     <xsl:text> </xsl:text> 
     <xsl:value-of select="@name"/> 
     <xsl:text>: </xsl:text> 
     <xsl:value-of select="."/> 
     <xsl:text>&#xa;</xsl:text> 
     </xsl:for-each> 
    </xsl:for-each> 
    </xsl:template> 

</xsl:stylesheet> 

應用到您輸入XML,

<FAMILY> 
    <FAMILY_NAMES id="1" name="Smith"> 
    <KID name="Jim">First Born</KID> 
    <KID name="Joe">Enjoys playing outside</KID> 
    <KID name="Jon">Straight A student</KID> 
    </FAMILY_NAMES> 
    <FAMILY_NAMES id="2" name="Barnes"> 
    <KID name="Mike">Just got his license</KID> 
    <KID name="Dan">On vacation</KID> 
    <KID name="Ken">Going to graduate school</KID> 
    </FAMILY_NAMES> 
    <FAMILY_NAMES id="3" name="Thompsons"> 
    <KID name="James">Loves sports</KID> 
    <KID name="Ben">Middle Child</KID> 
    <KID name="Frank">Youngest child</KID> 
    </FAMILY_NAMES> 
</FAMILY> 

產生以下的輸出:

Smith 
    Jim: First Born 
    Joe: Enjoys playing outside 
    Jon: Straight A student 
Barnes 
    Mike: Just got his license 
    Dan: On vacation 
    Ken: Going to graduate school 
Thompsons 
    James: Loves sports 
    Ben: Middle Child 
    Frank: Youngest child 
+0

非常感謝。這工作完美。它的格式也很好。我必須仔細閱讀並理解每一行。非常感謝。 – user1898629