0

你好!

我有一个问题,我试图根据一个子值删除元素(带子):这是 XML 示例:

    <?xml version="1.0" encoding="UTF-8"?>
    <Businesses>
    <Business NAME="busin1">
    <CHILD ID="30"><title>child Title</title>
    <description>Child Description</description>
    <urlToSite>http://www.MySite.co.il</urlToSite>
    <endtime>20120720103000</endtime>
    <starttime>20120710191500</starttime>
    </CHILD> 
<CHILD>...</CHILD>
<CHILD>...</CHILD>
</Business>
    </Businesses>

现在我需要删除其“结束时间”值比现在更旧的所有特定“儿童”元素(包括儿童)(或者只是“结束时间”等于特定值)

"endtime" 是一个日期,格式为:yyyymmddHHMMSS

这是我的第一次尝试(没有成功):

    $doc = new DOMDocument; 
    $doc->load('MyXML.xml'); //The XML Above

    $thedocument = $doc->documentElement;

    //this gives you a list of the childs
    $list = $thedocument->getElementsByTagName('CHILD');

    //figure out which ones you want -- assign it to a variable (ie: $nodeToRemove )
    $nodeToRemove = null;
$time=date("YmdHis",time ());
    foreach ($list as $domElement){
 $attrValue = $domElement->childNodes->item('endtime')->nodeValue; //not Sure about this!!
      if ($attrValue > $time) {
        $nodeToRemove = $domElement;
      }
    }

    //Now remove it.
    if ($nodeToRemove != null)
    $thedocument->removeChild($nodeToRemove);
    echo $doc->saveXML(); 

非常感谢!

4

2 回答 2

1

使用 XPath 查询文档节点。试试这个:

$maxTime = date("YmdHis", time());

$doc = new DOMDocument();
$doc->load("MyXML.xml");

$xpath = new DOMXPath($doc);
$q = "/Businesses/Bisiness/CHILD/endtime[. > {$maxTime}]";
foreach ($xpath->query($q) as $node) {
    $businessNode = $node->parentNode;
    $businessesNode = $businessNode->parentNode;
    $businessesNode->removeChild($businessNode);
}

这是一个带有 XPath 示例的好页面。

于 2012-07-27T11:00:43.067 回答
1

你好,我们又见面了!

经过一整天的研究..终于我找到了问题..

首先感谢迈克尔的帮助。

这是最终的工作代码:

<?php

$doc = new DOMDocument; 
$doc->load('MyXML.xml');

$maxTime = date("YmdHis", time());

$xpath = new DOMXPath($doc);
$q = "/Businesses/Bisiness/CHILD/endtime[. < {$maxTime}]";
foreach ($xpath->query($q) as $node) {
    $businessNode = $node->parentNode;
    $businessesNode = $businessNode->parentNode;
    $businessesNode->removeChild($businessNode);
}

// inserting to variable ONLY
$last = $doc->saveXml();
// IMPORTANT!! - we have to rewrite to XML the Results back!!
file_put_contents('MyXML.xml', $last)
?>

我没有在任何地方找到它,所以我希望这会对你有所帮助.. :)

于 2012-07-28T18:09:11.713 回答