我试图使设施的enddate高于20170199并且它是父级的,我试图让父级为::*的父级显示整个树,而不是筛选视图。
给定xml

<Delivery>
   <Person>
     <Name>John</Name>
     <LastName>Doe</LastName>
     <Facility>
       <TypeFacility>2</TypeFacility>
       <StartDate>20161131</StartDate>
       <EndDate>20161231</EndDate>
     </Facility>
     <Facility>
       <TypeFacility>2</TypeFacility>
       <StartDate>20161131</StartDate>
       <EndDate>20170231</EndDate>
     </Facility>
   </Person>
</Delivery>

到目前为止我试过的
<?php
$xmlStr = simplexml_load_file("test.xml");
$res = $xmlStr->xpath("Person/Facility[EndDate>20170199]/parent::*");
echo '<pre>';print_r($res);

预期结果
   <Person>
     <Name>John</Name>
     <LastName>Doe</LastName>
     <Facility>
       <TypeFacility>2</TypeFacility>
       <StartDate>20161131</StartDate>
       <EndDate>20170231</EndDate>
     </Facility>
   </Person>

实际结果
   <Person>
     <Name>John</Name>
     <LastName>Doe</LastName>
     <Facility>
       <TypeFacility>2</TypeFacility>
       <StartDate>20161131</StartDate>
       <EndDate>20161231</EndDate>
     </Facility>
     <Facility>
       <TypeFacility>2</TypeFacility>
       <StartDate>20161131</StartDate>
       <EndDate>20170231</EndDate>
     </Facility>
   </Person>

最佳答案

您需要的是过滤/移除所有具有值小于Facility的子EndDate节点的20170199节点(以保留值大于20170199的节点)。
使用DomDocumentDomXPath类的解决方案:

$doc = new DOMDocument();
//$doc->preserveWhiteSpace = false;
$doc->load("test.xml");

$person = $doc->getElementsByTagName('Person')->item(0);  // context node
$xpath = new DOMXPath($doc);

foreach ($xpath->query('Facility[EndDate <= 20170199]', $person) as $n) {
    $person->removeChild($n);
}
echo $doc->saveXML($person);

输出:
<Person>
     <Name>John</Name>
     <LastName>Doe</LastName>

     <Facility>
       <TypeFacility>2</TypeFacility>
       <StartDate>20161131</StartDate>
       <EndDate>20170231</EndDate>
     </Facility>
   </Person>

DEMO link

07-24 09:55