XPath查询返回不同级别的多个节点

时间:2013-09-29 11:55:53

标签: php xml xpath

PHP XPath查询:

$query = $xpathvar->query('//siri:Service');
foreach($query as $service) {
    echo $service->textContent;
    // Here I need to also echo this Vehicle's reg
}

目标XML:

<Vehicle>
    <CategoryA>
        <Service>123123123</Service>
    </CategoryA>
    <CategoryB>
         <SubCategoryA>
             <Reg>ASDF_XC1</Reg>
         </SubCategoryA>
    </CategoryB>
</Vehicle>
// Imagine many more vehicles here each with a service and reg

如何更改PHP以便我也检索每个的Reg?检索时服务和注册必须在同一车辆内(不是随机对)。

1 个答案:

答案 0 :(得分:3)

如何查询车辆然后将其用作上下文节点来搜索ServiceReg

$vehicles = $xpath->query('//siri:Vehicle');
$pairs = array();
foreach ($vehicles as $vehicle) {
    $pairs[] = array(
        'Service' => $xpath->evaluate('string(.//siri:Service)', $vehicle),
        'Reg'     => $xpath->evaluate('string(.//siri:Reg)'    , $vehicle),
    );
}

参见: