开发者

How i can edit a xml file using DOMDocument and xquery

开发者 https://www.devze.com 2023-01-23 10:44 出处:网络
I have a xml file <events date=\"06-11-2010\"> <event id=\"8\"> <title>Proin porttitor sollicitudin augue</title>

I have a xml file

<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&l开发者_如何转开发t;/title>
  <description><![CDATA[Lorem ipsum dolor sit amet]]></description></event></events>

How i can edit the xml file with respect to id using DOMDocument and xquery for preserving CDATA Thanks in advance

link text


First of all, your document has invalid XML syntax (the </createCDATASection> tag). 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>

Now, here's a solution to edit title/description for your event:

$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();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号