2016-11-29 62 views
3

我需要在saymfony中管理xml文档。如何将xml节点添加到symfony Crawler()

我已经没有问题将xml放入Crawler()实例中,修改现有节点并在其后将xml放入文件中。

但我无法添加新节点。

当我尝试用的appendChild方法一个新的节点添加到父,我有:

错误文档错误

,当我尝试add方法的履带,我有:

不可能为爬虫添加两个不同的来源?

我能做些什么来添加一个简单的节点到现有的履带?

感谢任何响应

回答

0

我有一个类似的问题给你,我想:

$crawler=new Crawler($someHtml); 
$crawler->add('<element />'); 

,并得到

附加DOM从多个文档中的节点在同一爬虫禁止。

随着DOMDocument,你用自己的方法createElement,使节点(S),然后将它们添加到文档与appendChild或什么的。但由于Crawler似乎没有像createElement这样的东西,我提出的解决方案是使用本地dom文档初始化Crawler,做任何你想用Crawler做的事情,但是然后使用dom文档作为“节点工厂“,当你需要添加一个节点。

我的具体情况是,我需要检查,如果一个文件有一个head,并添加一个(特别是添加它的身体标记以上),如果它没有:

 $doc = new \DOMDocument; 
     $doc->loadHtml("<html><body bgcolor='red' /></html>"); 
     $crawler = new Crawler($doc); 
     if ($crawler->filter('head')->count() == 0) { 
      //use native dom document to make a head 
      $head = $doc->createElement('head'); 
      //add it to the bottom of the Crawler's node list 
      $crawler->add($head); 
      //grab the body 
      $body = $crawler 
       ->filter('body') 
       ->first() 
       ->getNode(0); 
      //use insertBefore (http://php.net/manual/en/domnode.insertbefore.php) 
      //to get the head and put it above the body 
      $body->parentNode->insertBefore($head, $body); 
     } 

echo $crawler->html(); 

产生

<head></head> 
<body bgcolor="red"></body> 

它似乎有点复杂,但它的工作原理。我正在处理HTML,但我想象一个XML解决方案将几乎相同。