[英]How to loop through all same name parent and child nodes
我有一個 XML 文件,其中我有相同的名稱節點:父節點和子節點,例如:
<Root>
<Field name="ID">
<description>Test 1</description>
</Field>
<Field name="Period">
<description>Test 2</description>
<Field name="Name">
<description>Test 3</description>
</Field>
<Field name="Name2">
<description>Test 4</description>
<Field name="address">
<description>Test 5</description>
</Field>
<Field name="partyID">
<description>Test 6</description>
<Field name="E-ID">
<Field name="address">
<description>Test 7</description>
</Field>
</Field>
</Field>
</Field>
</Field>
</Root>
問題是,我不確定我們可以擁有多深的同名子元素:
我在頂級父節點上使用了模板匹配:
<xsl:template match="Field">
<xsl:value-of select="description"/>
<xsl:for-each select="Field">
<xsl:value-of select="description"/>
</xsl:for-each>
</xsl:template>
此代碼沒有為我提供所有子節點值。 我正在尋找一個可以遍歷所有同名節點並提供描述元素值的代碼。
我不能為每個添加多個,因為正如我所說,我們不知道在另一個 Field 節點中有多少次 Field 節點。
請幫我解決這個問題。
您可以使用遞歸來處理從樹的根到葉子的所有Field
元素 - 例如(您沒有發布預期的結果,所以我做了一些事情):
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/Root">
<output>
<xsl:apply-templates select="Field"/>
</output>
</xsl:template>
<xsl:template match="Field">
<desc>
<xsl:value-of select="description"/>
</desc>
<xsl:apply-templates select="Field"/>
</xsl:template>
</xsl:stylesheet>
或者,您可以只 select 所有Field
元素,而不管它們在樹層次結構中的 position:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/Root">
<output>
<xsl:for-each select="//Field">
<desc>
<xsl:value-of select="description"/>
</desc>
</xsl:for-each>
</output>
</xsl:template>
</xsl:stylesheet>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.