2013-03-01 37 views
0

xpath 1.0 - 我不得不改變方法,因爲XML已經改變。php xpath基於兩個屬性值(編輯)選擇節點及其父母的屬性

我需要拉

t-Attribute FROM the <d>-node WHERE its 
    raw-Attribute = 10 
    AND its parent-node's <scale> gender-Attribute = "*" OR "m" 
    AND the age-Attribute = "*" OR "39-59" 

<scales> 
    <scale id="1" gender="*" age="*"> 
     <d scid="hi" raw="10" t="76" /> 
     <d scid="pn" raw="12" t="80" /> 
    </scale> 
    <scale id="2" gender="m" age="*"> 
     <d scid="hi" raw="8" t="79" /> 
     <d scid="pn" raw="2" t="50" /> 
    </scale> 
    <scale id="3" gender="*" age="19-39"> 
     <d scid="hi" raw="0" t="48" /> 
     <d scid="pn" raw="10" t="49" /> 
    </scale> 
</scales> 

對於我原來的目標,路人的解決方案工作就像一個魅力,但我無法弄清楚如何解決額外的任務...

$result=$xml->xpath('//scale[@gender="*" or @gender="m"][@age="*" or @age="39-59"]'); 

這是我的原始任務...

我想從xml中選擇兩個屬性保存特定值的節點。我使用的是simplexml,因此xpath必須是1.0。

XML片段:

<scales> 
    <scale id="1" gender="*" age="*"> 
     <d>5</d> 
     <d>9</d> 
    </scale> 
    <scale id="2" gender="m" age="*"> 
     <d>3</d> 
     <d>0</d> 
    </scale> 
    <scale id="3" gender="*" age="19-39"> 
     <d>12</d> 
     <d>19</d> 
    </scale> 
</scales> 

現在,我想在我的例子選擇所有<scale>有...

(gender="*" OR gender="m") AND (age="*" OR age="39-59") 

與ID = 1個ID的那些= 2

我知道如何做1屬性,但沒有OR/AND條件...

$scales=$xml->xpath("//scale[@gender='m']"); 

回答

1

嘗試

//scale[@gender="*" or @gender="m"][@age="*" or @age="39-59"] 

Live demo

$str=<<<XML 
<scales> 
    <scale id="1" gender="*" age="*"> 
     <d>5</d> 
     <d>9</d> 
    </scale> 
    <scale id="2" gender="m" age="*"> 
     <d>3</d> 
     <d>0</d> 
    </scale> 
    <scale id="3" gender="*" age="19-39"> 
     <d>12</d> 
     <d>19</d> 
    </scale> 
</scales> 
XML; 
$xml=simplexml_load_string($str); 
$result=$xml->xpath('//scale[@gender="*" or @gender="m"][@age="*" or @age="39-59"]'); 
foreach($result as $node) 
{ 
    echo $node->attributes()->id."\n"; 
} 
+0

太棒了,謝謝! – michi 2013-03-01 12:04:43

+0

不得不用這個xpath來調整我的目標,你可以看看它,如果它對你沒問題嗎? http://stackoverflow.com/questions/15158314/php-xpath-retrieving-attribute-values-based-on-multiple-attributes-and-parent-at#comment21344739_15158314 – michi 2013-03-01 13:14:30

相關問題