如何在XML的第一个元素之前插入子注释?

时间:2013-07-11 13:14:10

标签: php xml xpath xml-parsing

<source>        
    <job>
    <title><![CDATA[newsTitle]]></title>
    <date><![CDATA[newsTo]]></date>
     .......

现在,我需要添加

<publisher>abc</publisher>
<publisherurl>http://google.com</publisherurl>    

<source>标记之后。我尝试了以下代码,但它是在源代码之后添加的!

$doc = new DOMDocument();
$doc->load('C:\test.xml', LIBXML_NOBLANKS);    
$xpath = new DOMXPath($doc);
$hrefs = $xpath->evaluate("/source");
$href = $hrefs->item(0);   
$link = $doc->createElement("publisher","abc");
$href->appendChild($link);
$link = $doc->createElement("publisherurl","www.google.com");
$href->appendChild($link);

print $doc->save('C:\test.xml');

如何在源代码后面添加这些节点?

3 个答案:

答案 0 :(得分:2)

使用DOMNode::insertBefore

参考php参考页面中给出的示例

答案 1 :(得分:2)

<?php
$rssDoc = new DOMDocument();
$rss_file = 'C:\test.xml';
$rssDoc->load($rss_file);
$items = $rssDoc->getElementsByTagName('source');

$firstItem = $items->item(0);

$newItem[] = $rssDoc->createElement('lastBuildDate', 'Fri, 10 Dec 2008 22:49:39 GMT');
$newItem[] = $rssDoc->createElement('publisherurl', 'http://www.xyz.com');
$newItem[] = $rssDoc->createElement('publisher', 'XYZ');
foreach ($newItem as $xmlItem){
 $firstItem->insertBefore($xmlItem,$firstItem->firstChild);
} 

echo $rssDoc->save('C:\test.xml');
?>
嘿,Manoj Kumar,这应该适合你。试试这个。 :)

答案 2 :(得分:0)

最后我找到了解决方案。我仍然很少有疑问,

$rssDoc = new DOMDocument();
$rss_file = 'C:\test.xml';
$rssDoc->load($rss_file);
$items = $rssDoc->getElementsByTagName('source');

$newItem = $rssDoc->createElement('lastBuildDate', 'Fri, 10 Dec 2008 22:49:39 GMT');
$rssDoc->appendChild($newItem);
$firstItem = $items->item(0);
$firstItem->insertBefore($newItem,$firstItem->firstChild);

$newItem = $rssDoc->createElement('publisherurl', 'http://google.com');
$rssDoc->appendChild($newItem);
$firstItem = $items->item(0);
$firstItem->insertBefore($newItem,$firstItem->firstChild);

$newItem = $rssDoc->createElement('publisher', 'newschannel');
$rssDoc->appendChild($newItem);
$firstItem = $items->item(0);
$firstItem->insertBefore($newItem,$firstItem->firstChild);

echo $rssDoc->saveXML();

是否有可能在循环中一个接一个地附加这些孩子,并在类似之前插入它?