好吧,由于速度和_why的消失,从工作的Hpricot切换到Libxml-ruby,看了一下Nokogiri,但决定看看Libxml-ruby的速度和寿命。我肯定遗漏了一些基本的东西,但我尝试做的是不起作用的,下面是我的XML字符串:
<?xml version="1.0" encoding="utf-8" ?>
<feed>
<title type="xhtml"></title>
<entry xmlns="http://www.w3.org/2005/Atom">
<id>urn:publicid:xx.xxx:xxxxxx</id>
<title>US--xxx-xxxxx</title>
<updated>2009-08-19T15:49:51.103Z</updated>
<published>2009-08-19T15:44:48Z</published>
<author>
<name>XX</name>
</author>
<rights>blehh</rights>
<content type="text/xml">
<nitf>
<head>
<docdata>
<doc-id regsrc="XX" />
<date.issue norm="20090819T154448Z" />
<ed-msg info="Eds:" />
<doc.rights owner="xx" agent="hxx" type="none" />
<doc.copyright holder="xx" year="2009" />
</docdata>
</head>
<body>
<body.head>
<hedline>
<hl1 id="headline">headline</hl1>
<hl2 id="originalHeadline">blah blah</hl2>
</hedline>
<byline>john doe<byttl>staffer</byttl></byline>
<distributor>xyz</distributor>
<dateline>
<location>foo</location>
</dateline>
</body.head>
<body.content>
<block id="Main">
story content here
</block>
</body.content>
<body.end />
</body>
</nitf>
</content>
</entry>
</feed>完整提要中大约有150个这样的条目。
我只想遍历150个条目,然后抓取内容和属性,但我在使用libxml时遇到了麻烦-ruby让它在Hpricot上工作得很好。
这个小代码片段显示,我甚至没有得到条目:
parser = XML::Parser.string(file)
doc = parser.parse
entries = doc.find('//entry')
puts entries.size
entries.each do |node|
puts node.inspect
end 有什么想法吗?我看了一遍文档,找不到简单的方法,这是一个XML文件,这是生成x,y,z的示例,这应该很简单。
发布于 2011-03-13 04:15:25
事实证明,Nokogiri具有一定的速度和寿命,因此这里有一些关于如何处理示例XML中的名称空间的示例。我使用Nokogiri作为一个大型的RDF/RSS/Atom聚合器,它每天处理数千个提要,使用类似的东西来获取我想要的字段,然后将它们推送到后端数据库中。
require 'nokogiri'
doc = Nokogiri::XML(file)
namespace = {'xmlns' => 'http://www.w3.org/2005/Atom'}
entries = []
doc.search('//xmlns:entry', namespace).each do |_entry|
entry_hash = {}
%w[title updated published author].each do |_attr|
entry_hash[_attr.to_sym] = _entry.at('//xmlns:' << _attr, namespace).text.strip
end
entry_hash[:headlines] = _entry.search('xmlns|hedline > hl1, xmlns|hedline > hl2', namespace).map{ |n| n.text.strip }
entry_hash[:body] = _entry.at('//xmlns:body.content', namespace).text.strip
entry_hash[:title] = _entry.at('//xmlns:title', namespace).text
entries << entry_hash
end
require 'pp'
pp entries
# >> [{:title=>"US--xxx-xxxxx",
# >> :updated=>"2009-08-19T15:49:51.103Z",
# >> :published=>"2009-08-19T15:44:48Z",
# >> :author=>"XX",
# >> :headlines=>["headline", "blah blah"],
# >> :body=>"story content here"}]Nokogiri中的CSS和XPath都可以处理名称空间。Nokogiri将通过获取根节点中定义的所有名称空间来简化它们的使用,但在此XML示例中,名称空间是在entry节点中定义的,让我们手动完成此操作。
我切换到标题的CSS表示法,只是为了展示如何做它们。为了方便起见,如果能够找到名称空间声明,Nokogiri通常会允许CSS使用通配符的名称空间,这会将hl1节点的访问器简化为'|headline > hl1'。
发布于 2009-08-23 16:35:10
我怀疑你有问题,因为在你的发现中跳过了名称空间。如果你看看xpath documentation for libxml-ruby,他们有一些非常相关的例子。具体来说,您的查找应该类似entries = doc.find('//atom:entry','atom:http://www.w3.org/2005/Atom'),因为它的格式是正确的。
https://stackoverflow.com/questions/1318928
复制相似问题