[英]Searching for tags while parsing Wordpress XML with Nokogiri
我有一个Wordpress博客的XML文件,其中包含引号:
<item>
<title>Brothers Karamazov</title>
<content:encoded><![CDATA["I think that if the Devil doesn't exist and, consequently, man has created him, he has created him in his own image and likeness."]]></content:encoded>
<category domain="post_tag" nicename="dostoyevsky"><![CDATA[Dostoyevsky]]></category>
<category domain="post_tag" nicename="humanity"><![CDATA[humanity]]></category>
<category domain="category" nicename="quotes"><![CDATA[quotes]]></category>
<category domain="post_tag" nicename="the-devil"><![CDATA[the Devil]]></category>
</item>
我想要提取的东西是标题,作者,内容和标签。 到目前为止,这是我的代码:
require "rubygems"
require "nokogiri"
doc = Nokogiri::XML(File.open("/Users/charliekim/Downloads/quotesfromtheunderground.wordpress.2013-04-14.xml"))
doc.css("item").each do |item|
title = item.at_css("title").text
tag = item.at_xpath("category").text
content = item.at_xpath("content:encoded").text
#each post will later be pushed to an array, but I'm not worried about that yet, so for now....
puts "#{title} #{tag}"
end
我很难从每个item
获取所有标签。 我得到的回报就像Brothers Karamazov Dostoyevsky
。 我并不担心它是如何格式化的,因为它只是一个测试,看它是正确的选择。 谁知道我怎么能这样做?
我也想制作大写的标签=作者,所以如果你知道怎么做,它也会有所帮助,虽然我还没有尝试过。
编辑:我将代码更改为:
doc.css("item").each do |item|
title = item.at_css("title").text
content = item.at_xpath("content:encoded").text
tag = item.at_xpath("category").each do |category|
category
end
puts "#{title}: #{tag}"
end
返回:
Brothers Karamazov: [#<Nokogiri::XML::Attr:0x80878518 name="domain" value="post_tag">, #<Nokogiri::XML::Attr:0x80878504 name="nicename" value="dostoyevsky">]
而且似乎更容易管理。 它搞砸了我从大写标签中获取作者的计划,但是,这并不是一笔交易。 我怎么能拉第二个value
?
当at_
方法只返回第一个结果时,你正在使用at_xpath
并期望它返回多个结果。
你想要的东西:
tags = item.xpath("category").map(&:text)
这将返回一个数组。
至于识别作者,您可以使用正则表达式来选择以大写字母开头的项目:
author = tags.select{|w| w =~ /^[A-Z]/}
哪个会选择任何大写的标签。 这使得标签保持不变。 如果您希望将作者与标记分开,则可以使用partition
:
author, tags = item.xpath("category").map(&:text).partition{|w| w =~ /^[A-Z]/}
请注意,在上面的示例中,author是一个数组,将包含所有匹配的项(即多个大写标记)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.