我有一个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
提前致谢
链接文字
答案 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();