加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何将xml节点添加到symfony Crawler()

发布时间:2020-12-16 23:28:32 所属栏目:百科 来源:网络整理
导读:我需要在saymfony中管理xml文档. 我没有问题将xml放入Crawler()实例,修改现有节点,然后将xml放入文件中. 但我无法添加新节点. 当我尝试将一个带有appendChild方法的新节点添加到父节点时,我得到了: wrong document error 当我尝试向抓取工具添加方法时,我得
我需要在saymfony中管理xml文档.

我没有问题将xml放入Crawler()实例,修改现有节点,然后将xml放入文件中.

但我无法添加新节点.

当我尝试将一个带有appendChild方法的新节点添加到父节点时,我得到了:

wrong document error

当我尝试向抓取工具添加方法时,我得到了:

impossible to add two differents sources to the crawler?

如何将简单节点添加到现有爬网程序?

谢谢你的回复

解决方法

我有一个类似的问题,我试过:

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

得到了

Attaching DOM nodes from multiple documents in the same crawler is forbidden.

使用DOMDocument,您可以使用自己的createElement方法创建节点,然后使用appendChild或其他任何方法将它们附加到文档.但是由于Crawler似乎没有像createElement那样的东西,我想出的解决方案是使用本机dom文档初始化Crawler,做任何你想用Crawler做的事情,但是然后使用dom文档作为“节点”工厂“当你需要添加一个节点.

我的特殊情况是我需要检查一个文件是否有一个头,并添加一个(特别是将其添加到body标签上方),如果它没有:

$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解决方案几乎是一样的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读