2017-10-14 23 views
0

我希望獲得所有直屬子集的所有義和團名單。僅訪問HTML集合中返回的項目的直接子項

XML由外部來源提供。我無法控制其內容或格式。

Boxer標籤通過Match標籤被用作Group的直接子代,也可用作Group的孫子。

<Round PhaseID="2" ID="Round 1"> 
    <Boxer REF="2"/> 
    <Boxer REF="3"/> 
    <Boxer REF="4"/> 
    <Boxer REF="1"/> 

    <Group ID="1"> 
     <Boxer REF="1" NumInGroup="2" NumVictories="0" NumMatches="2" PtsFor="0" PtsAgainst="0" GroupId="1"/> 
     <Boxer REF="4" NumInGroup="1" NumVictories="0" NumMatches="2" PtsFor="0" PtsAgainst="0" GroupId="1"/> 
     <Match ID="1"> 
     <Boxer REF="1"/> 
     <Boxer REF="4"/> 
     </Match> 
     <Match ID="2"> 
     <Boxer REF="4"/> 
     <Boxer REF="1"/> 
     </Match> 
    </Group> 
    ... 
</Round> 

當我使用

var groups = competitionDoc.getElementsByTagName("Group"); 
var boxers = groups[0].getElementsByTagName("Boxer"); 

我得到一個名爲「義和團」的所有6個標籤受到本集團標籤的後裔的名單。

我如何獲得團體的兩個直接子女?

+0

我可以看到.parentElement屬性包含的信息。有沒有一種方法來修剪基於parentElement的HTMLcollection? –

回答

0

當我迭代組[g] .getElementsByTagName(「Boxer」)返回的所有元素時,我將parentElement信息轉換爲字符串,然後我可以使代碼在第一個子字符串上有條件。

要打開groupBoxers [GB] .parentElement成字符串:

groupBoxers[gb].parentElement.outerHTML 

它返回,例如

<Group ID="1"> 
    <Boxer REF="1" NumInGroup="2" NumVictories="0" NumMatches="2" PtsFor="0" PtsAgainst="0" GroupId="1"/> 
    <Boxer REF="2" NumInGroup="1" NumVictories="0" NumMatches="2" PtsFor="0" PtsAgainst="0" GroupId="1"/> 

    <Match ID="1"> 
    <Boxer REF="1"/> 
    <Boxer REF="2"/> 
    </Match> 

</Group> 

然後我通過組[G] .getElementsByTagName(「義和拳」)返回的所有元件進行迭代,我可以

if (groupBoxers[gb].parentElement.outerHTML.substring(1,6) == "Group") { 
    // do something with this Boxer - it is a direct child of a Group 
    } 
相關問題