0

我正在尝试选择一个特定节点以稍后编辑其内容和属性,但我无法选择一个notice节点(请参阅下面的 PHP 代码)。

XML 文档

<?xml version="1.0" encoding="UTF-8"?>
<notices lastID="0001">
    <!--
    <notice id="0000" endDate="31-12-2025">
        Content of the notice.
    </notice>
    -->
    <notice id="0001" endDate="13-01-2013" active="1">
        One amazing notice.
    </notice>

</notices>

$id值为“0001”(字符串)。

PHP

$document = new DOMDocument;
$document = dom_import_simplexml($this->xml);

$notices= $document->getElementsByTagName('notice');
#var_dump($notices);

foreach($notices as $element)
{
    if($element->getAttribute('id') == $id)
    {
        $notice = $element;
        var_dump($notice); //Returns absolutely nothing (I guess the if returns false).
    }
}

$notice->removeAttribute("endDate");
$notice->setAttribute("endDate",$endDate);

每次我落入if声明中,我的$notice回报都没有。
我尝试使用 xpath 查询(//notice[@id="{$id}"])没有任何成功。

澄清一下,我的问题$element->getAttribute('id')似乎不起作用。


我也尝试过SimpleXML

PHP

$document = new DOMDocument;
$document = simplexml_import_dom($this->xml);

$notice = "";

foreach($document->notices->children() as $element)
{
    $attributes = $element->attributes();
    if($attributes['id'] == $id)
    {
        $notice= $element;
        var_dump($notice);
    }
}
$avis->removeAttribute("endDate");
$avis->setAttribute("endDate",$endDate);

SimpleXML 给了我以下信息:Node no longer exists在下面一行:

foreach($document->notices->children() as $element)

4

1 回答 1

0

我终于明白了。

PHP

$document = simplexml_import_dom($this->xml);
$notice = "";

$xpathResults = $document->xpath('//notice');


foreach($xpathResults as $element)
{
    $elementID = $element->id[0];
    $domXML = dom_import_simplexml($element);

    if((string) $noticeID == $id)
    {
        $notice = $domXML;

    }
}
于 2013-01-09T18:22:33.400 回答