PHP XPath - 使用一个规则选择一个特定节点及其父节点

时间:2013-08-21 15:05:11

标签: php xpath

我正在使用Xpath解析一些XML文件。我想用一个表达式选择一个特定的Category节点和他的父节点(Sport)?!

XML文档:livescore_full.xml

<? xml version = "1.0" encoding = "UTF-8" ?>
<LivescoreData generatedAt="2013-08-18T09:41:19 CEST" type="full">
    <Sport SportId="1">
        <Name language="en">Soccer</Name>
        <Category CategoryId="48">
            <Name language="en">Argentina</Name>
            <Tournament TournamentId="68" UniqueTournamentId="155">
                <Name language="en">Primera Division, Torneo Inicial</Name>
            </Tournament>
        </Category>
        <Category CategoryId="49">
            <Name language="en">Brazil</Name>
            <Tournament TournamentId="69" UniqueTournamentId="156">
                <Name language="en">Brazil Primera Division</Name>
            </Tournament>
        </Category>
    </Sport>
    <Sport SportId="2">
        <Name language="en">Basketball</Name>
        <Category CategoryId="55">
            <Name language="en">Spain</Name>
            <Tournament TournamentId="545" UniqueTournamentId="453">
                <Name language="en">Primera Division, Torneo Inicial</Name>
            </Tournament>
        </Category>
        <Category CategoryId="56">
            <Name language="en">England</Name>
            <Tournament TournamentId="654" UniqueTournamentId="5656">
                <Name language="en">England</Name>
            </Tournament>
        </Category>
    </Sport>
</LivescoreData>


 $xml = simplexml_load_file("livescore_full.xml");
 $data = $xml->xpath('//Category[@CategoryId="48"]'); 
 print_r($data); // only return data for specific Category node

$ data 包含有关类别节点ID = 48的数据,但没有关于运动ID和运动名称的信息。

如何编写Xpath规则以使用CategoryId属性选择Sport和Category数据?我尝试了祖先或自我的一些变体,但没有成功。

2 个答案:

答案 0 :(得分:0)

"/LiveScoreData/Sport[Category[@CategoryId='48']"

将是一种方式。

答案 1 :(得分:0)

我想到的一个简单答案是(How do I select multiple nodesets):

$data = $xml->xpath('//Category[@CategoryId="48"] | //Sport[Category[@CategoryId="48"]]');

但是,我会针对这种情况放弃SimpleXML并执行此操作:

 $dom = new DOMDocument();
 $dom->load("livescore_full.xml");
 $xpath = new DOMXPath($dom);
 $category = $xpath->query('//Category[@CategoryId="48"]')->item(0);
 //then sport is just it's parentNode:
 $sport = $category->parentNode; 

 //removing all other cats:
 $dom = new DOMDocument();
 $dom->load("livescore_full.xml");
 $xpath = new DOMXPath($dom);

 $categories = $xpath->query('//Sport[Category[@CategoryId="48"]]/Category[@CategoryId!="48"]');
 while($othercat = $categories->item(0)){
     $othercat->parentNode->removeChild($othercat);
 }