我正在使用DOMDocument来解析html文档并从中获取一些数据。以下是DOM
的子树结构<div id="tab1">
<div class="some class name"></div>
<div class="some other class name">arbitrary data and nodes</div>
<p> lot of paragraphs to follow </p>
<p> paragraphs </p>
<p> paragraphs </p>
<p> paragraphs </p>
<p> paragraphs </p>
<br />
<br />
<br />
<br />
<br />
<table />
<table />
<table />
<table />
</div>
我不想要tab1的前两个孩子。我正在使用以下PHP代码
<?php
$urlArray = file('sitemap.txt');
$dataSet = array();
foreach($urlArray as $url){
$scrapedData = file_get_contents('./scraped-site/'.trim($url));
$doc = new DOMDocument();
@$doc->loadHTML($scrapedData);
$domXpathDoc = new DOMXPath($doc);
$results = '';
$xpathArray = array(
'info'=>'//*[@id="tabs1"]',
);
$set = array();
foreach($xpathArray as $field => $xpath){
$domNodeList = $domXpathDoc->query($xpath);
foreach($domNodeList as $node){
foreach ($node->childNodes as $child) {
$set[] = $child->ownerDocument->saveXML( $child );
}
}
}
$dataSet[] = $set;
}
给出的代码给了我所有的孩子如何有选择地避免任何节点?
答案 0 :(得分:1)
[EDIT2:我尝试了下面的答案(我学到了:))。这对我有用:
"//*[@id='tabs1'][name() != 'div']"
基本上它告诉xpath忽略所有名为'div'的元素。您可以忽略多个这样的元素:
"//*[@id='tabs1'][name() != 'div' and name() != 'foo']"
只有在前两个元素之后显示元素才会这样:
"//*[@id='tabs1'][position()>2]"