2013-03-01 38 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

相关问题