2012-09-12 92 views
0

如何打印能力 -elements 默認 - 如果您只有元素的名稱和能力ID,那麼對以下XML具有屬性值?僅通過名稱和屬性值使用PHP DOM訪問XML元素?

例如,如果我有'steve'這個名字,並且ID爲1003,那麼我將如何選擇並打印該屬性爲'false'的默認值。

<Item Id="1"> 
<Name>Batman</Name> 
<Ability Id="3001" Default="true">Super Strength</Ability> 
<Ability Id="3002" Default="false">Master martial artist</Ability> 
<Ability Id="3003" Default="false">Access to high tech</Ability> 
</Item> 

<Item Id="2"> 
<Name>Superman</Name> 
<Ability Id="3004" Default="true">Flight</Ability> 
<Ability Id="3005" Default="false">Super Strength</Ability> 
<Ability Id="3006" Default="false">Super Speed</Ability> 
<Ability Id="3007" Default="true">Stamina</Ability> 
<Ability Id="3008" Default="false">Invulnerability</Ability> 
</Item> 

<Item Id="3"> 
<Name>Spiderman</Name> 
<ScopeNotes/> <HistoryNotes/> 
<Ability Id="219" Default="false">Super Reflex & Agility</Ability> 
<Ability Id="567" Default="true">Spider Sense</Ability> 
</Item> 

<Item Id="4"> 
<Name>Steve</Name> 
<Ability Id="1007" Default="false">Cake eating</Ability> 
<Ability Id="1001" Default="true">Swearing</Ability> 
<Ability Id="1002" Default="false">Watching movies</Ability> 
<Ability Id="1003" Default="false">Steve</Ability> 
</Item> 

的問題是,每個元件具有不同數量的能力的節點,並且名稱爲「史蒂夫」無論是在名稱和能力節點發生。

我已閱讀了php dom文檔,並使用它來遍歷項目並獲取名稱(例如,新的DOMDocument,加載文件,getElementsByTagName),但我很難理解它是如何工作的,當您嘗試做類似我在上面解釋過。

+0

也許考慮的XPath,它是一個XML文檔中的信息查詢功能非常強大 –

回答

1

正如Bob Fincheimer所建議的,XPath應該是一個好方法。 下面的路徑應該給你的結果

//Item[Name="Steve"]/child::Ability[@Id="1003"]/@Default 

路徑的說明:在文檔中

  1. //
    選擇節點無處不在(我不知道完整的XML)
  2. Item
    select <Item> -nodes
  3. [Name="Steve"]
    個 有一個子元素<Name>用的nodeValue 「史蒂夫」
  4. child::Ability
    選擇子節點<Ability>選擇節點
  5. [@Id="1003"]
    建立ID屬性設置爲1003
  6. @Default
    選擇節點選擇默認屬性

對於給定的XML,它將返回一個帶有1個屬性節點的DOMNodeList (@Default="false")

如何使用它? http://www.php.net/manual/de/domxpath.query.php

演示:http://codepad.org/qtgWXFtm