-1
<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');

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

4

3 回答 3

2

使用DOMNode::insertBefore

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

于 2013-07-12T06:39:35.220 回答
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,这应该适合你。尝试这个。:)

于 2013-07-12T06:58:16.917 回答
1

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

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

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

于 2013-07-11T15:22:56.743 回答