我如何使用DOMDocument和xquery编辑xml文件

时间:2010-11-05 13:15:09

标签: php xml edit domdocument

我有一个xml文件

<events date="06-11-2010">
    <event id="8">
      <title>Proin porttitor sollicitudin augue</title>
      <description><![CDATA[Lorem  nunc.]]></description>
    </event>
  </events>
  <events date="16-11-2010">
    <event id="4">
      <title>uis aliquam dapibus</title>
      <description><![CDATA[consequat vel, pulvinar.</createCDATASection></description>
    </event>
  <event id="1"><title>You can use HTML and CSS</title>
  <description><![CDATA[Lorem ipsum dolor sit amet]]></description></event></events>

如何使用DOMDocument和xquery编辑关于id的xml文件以保留CDATA提前致谢

链接文字

1 个答案:

答案 0 :(得分:2)

首先,您的文档包含无效的XML语法(</createCDATASection>标记)。 FTFY:

<events date="06-11-2010">
  <event id="8">
    <title>Proin porttitor sollicitudin augue</title>
    <description><![CDATA[Lorem  nunc.]]></description>
  </event>
</events>
<events date="16-11-2010">
  <event id="4">
    <title>uis aliquam dapibus</title>
    <description><![CDATA[consequat vel, pulvinar.]]></description>
  </event>
  <event id="1">
    <title>You can use HTML and CSS</title>
    <description><![CDATA[Lorem ipsum dolor sit amet]]></description>
 </event>
</events>

现在,这是一个编辑事件标题/描述的解决方案:

$dom = new DOMDocument;
$dom->loadXML(file_get_contents('doc.xml'));

$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//event[@id="4"]/title | //event[@id="4"]/description');

// title
$node = $nodes->item(0);
$node->nodeValue = 'hello world';

// description
$node = $nodes->item(1);
$cdata = $node->firstChild;
$cdata->replaceData(0, strlen($cdata->data), 'hello world description');

print $dom->saveXML();