简单XML - 如何选择具有特定属性值的所有元素
问题描述:
用户可以选择一个性能,以便性能元素具有唯一的ID。我想基本上说:简单XML - 如何选择具有特定属性值的所有元素
选择所有保留 - >预订['座位']从演出 - >表演['id = 2']。
希望这是有道理的,我真的很努力与简单的XML选择。
在此先感谢,亨利。
<performances>
<performance id="7" time="12:00" day="Monday" month="June" year="2010">
<reservations>
<reservation seat="a7"/>
<reservation seat="a2"/>
<reservation seat="a3"/>
</reservations>
</performance>
<performance id="8" time="12:00" day="Tuesday" month="June" year="2010">
<reservations>
<reservation seat="a8"/>
</reservations>
</performance>
</performances>
额外的信息:
我目前正在使用:echo $xml2->show->performances->performance['0']->reservations->reservation['seat']
这得到一个预约从第一次演出,但我想从性能上都保留有“3”例如ID 。
答
你的 “SQL”:
SELECT reservations->reservation['seat'] FROM performances->performance['id=2']
可以被改写为:
FROM performances->performance['id=2'] SELECT reservations->reservation['seat']
可以重新为XPath的:
//performances/performance[@id=2]/reservations/reservation/@seat
蚂蚁这就是你所需要的。看看SimpleXML's xpath()
method。
答
<?php
// create a variable repsresenting the xml to parse through
$string = '<performances>
<performance id="7" time="12:00" day="Monday" month="June" year="2010">
<reservations>
<reservation seat="a7"/>
<reservation seat="a2"/>
<reservation seat="a3"/>
</reservations>
</performance>
<performance id="8" time="12:00" day="Tuesday" month="June" year="2010">
<reservations>
<reservation seat="a8"/>
</reservations>
</performance>
</performances>';
// create a variable representing a SimpleXMLElement instance
$xml = simplexml_load_string($string);
// create a variable representing the desired results, using the xpath method for
// the SimpleXMLElement instance previously created.
$results = $xml->xpath('//performances/performance[@id=2]/reservations/reservation/@seat');
?>
对不起,偷Tomalak的雷声在这里。有些人需要它有时拼写出来。
+0
Hey Cory,我对XML和XPATH都很陌生,所以我很难理解这个概念。 我不认为你会知道是否有可能使用xpath写入(addAtrribute)? – Henryz 2010-08-09 08:24:14
[SimpleXML:选择具有某个属性值的元素]的可能重复(http://*.com/questions/992450/simplexml-selecting-elements-which-have-a-certain-attribute-value) – hakre 2013-10-26 19:50:51