注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

淘尽网 官方博客

淘尽网http://www.tao3w.com做最好的比价网站

 
 
 

日志

 
 
关于我

淘尽网 http://www.tao3w.com 做最好的比价网站,做最好的数据抓取专家。

网易考拉推荐

QueryPath 中读取节点文本的问题  

2012-01-07 15:37:13|  分类: PHP |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

http://groups.google.com/group/support-querypath/browse_thread/thread/c709208d5266e98a

Problem:

a xml doc like this,

<root> 
    <c1> 11</c1> 
    <c2> 222<c3>333</c3></c2> 
</root>

how can I get the 222? I use text(), but it will return 222333. I have 
carefully read the doc and source of querypath, but there isn't a 

proper method.

Thanks a lot.

Answer:

This is a great question, and one that's bothered me for a while. It 
seems like there ought to be a straightforward way of doing this with 
the existing API, but it's actually more complicated than it sounds. 
Perhaps I should add a new method for just this sort of thing.

Anyway, here are two ways of doing this. I happen to think that the 
first way is really ugly... but it works:

$test = '<?xml version="1.0"?> 
<root> 
   <c1> 11</c1> 
   <c2> 222<c3>333</c3></c2> 
</root>';

// Get rid of competing children 
$qp = qp($test, 'c2'); 
$qp->branch()->children('c3')->remove(); 
print $qp->text();

// Get just the first DOMNode and fetch its text. We 
// use contents() because it returns text nodes as 
// well as elements. 
print qp($test, 'c2')->contents()->get(0)->textContent;

This second example can be altered to get *all text in the immediate 
element*, but none from the child elements:

$nodes = qp($test, 'c2')->contents()->get();

foreach ($nodes as $node) { 
  if ($node->nodeType == XML_TEXT_NODE) { 
    print $node->textContent; 
  }



Again, not pretty... but that's how to do it. 
Matt
  评论这张
 
阅读(202)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017