简体   繁体   English

Nokogiri用xpath解析XML

[英]Nokogiri parse XML with xpath

Im trying to figure out how to parse returned XMl via an api call, Im using Nokogiri and am trying to use xpath. 我试图找出如何通过api调用解析返回的XMl,我使用Nokogiri并尝试使用xpath。 What i would like to do is display all "title" attributes that have been returned 我想要做的是显示已返回的所有“标题”属性

So far i have in a method 到目前为止,我有一个方法

def getcontact
doc = Nokogiri::XML(open(url))
doc.xpath('//xmlns:feed/xmlns:entry')
end

controller 调节器

@mycontacts = getcontact

View 视图

<% @mycontacts.each do |c| %>
 <%= c.xpath("//title") %>
<% end %>

The XML XML

<entry>
 <id>xxx</id>
 <updated>xxx</updated> 
 <category  scheme="xxx"  term="xxx"/>
 <title type="text">xxx</title>
 <link rel="xxx" type="xxx"    href="xxx"/> 
 <link rel="xxx0gmail.com/b6ea0e8ddbc4e5"/>     
 <link rel="xx" type="xxx" href="xxx"/> <link rel="xx" type="axx" href="xxx"/> 
 <gd:email rel="xxx" address="xxx" primary="xx"/> 
</entry>

i am getting nothing returned, could someone point out what i am doing wrong please, also i notice there is html tags in the returned XML, can i strip this out, for example type=text is within the title attribute 我没有得到任何回报,有人可以指出我做错了吗,我也注意到返回的XML中有html标签,我可以将其删除,例如type = text在title属性中

Update 更新

So i have tried this 所以我试过这个

doc.xpath('//xmlns:feed/xmlns:entry/xmlns:title').text

but this returns all the titles as a string 但这会将所有标题作为字符串返回

Update 2 更新2

View 视图

<% @mycontacts.each do |c| %>
 <%= c.xpath('xmlns:title').text %><br>
<% end %>

method 方法

doc.xpath('//xmlns:feed/xmlns:entry')

so this lists all my titles but if there are any blank entries there is an empty record. 所以这列出了我的所有标题,但如果有任何空白条目,则会有一个空记录。 Need to remove these from the loop now i guess 我想现在需要从循环中删除这些

Is this correct, is there a better way to do it? 这是正确的,还有更好的方法吗?

Thanks 谢谢

With method 2, try using: 使用方法2,尝试使用:

d.xpath('//feed/entry[title[node()]]'

This will return a nodeset containing nodes that have a non-empty title. 这将返回包含具有非空标题的节点的节点集。 Then you can iterate over set however you like. 然后你可以迭代你喜欢的集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM