繁体   English   中英

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

[英]How i can edit a xml file using DOMDocument and xquery

我有一个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提前感谢

链接文字

首先,您的文档具有无效的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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM