我试图从这个XML中只检索两小部分信息。 id
(choice_xxxxxx)和description
(true / false):
<choices>
<component>
<id>choice_6WFRvQrXAN7</id>
<description lang="und">True</description>
</component>
<component>
<id>choice_5xBWm5NQRkA</id>
<description lang="und">False</description>
</component>
</choices>
但是因为我在Nokogiri中解析了这个,所以信息会像这样返回:
=> 0;34#(Element:0x3feeeb4301b0 {
name = "choices",
namespace = 0;34#(Namespace:0x3feeeb6f1fac {
href = "http://website.myxml.xsd"
}),
children = [
0;34#(Text "\n\t\t\t\t"),
0;34#(Element:0x3feeea7e36b4 {
name = "component",
namespace = 0;34#(Namespace:0x3feeeb6f1fac {
href = "http://website.myxml.xsd"
}),
children = [
0;34#(Text "\n\t\t\t\t\t"),
0;34#(Element:0x3feeea7e624c {
name = "id",
namespace = 0;34#(Namespace:0x3feeeb6f1fac {
href = "http://website.myxml.xsd"
}),
children = [ 0;34#(Text "choice_6WFRvQrXAN7")]
}),
0;34#(Text "\n\t\t\t\t\t"),
0;34#(Element:0x3feeea7e4a50 {
name = "description",
namespace = 0;34#(Namespace:0x3feeeb6f1fac {
href = "http://website.myxml.xsd"
}),
attributes = [
0;34#(Attr:0x3feeea7e86c8 { name = "lang", value = "und" })],
children = [ 0;34#(Text "True")]
}),
0;34#(Text "\n\t\t\t\t")]
}),
0;34#(Text "\n\t\t\t\t"),
0;34#(Element:0x3feeea7ea34c {
name = "component",
namespace = 0;34#(Namespace:0x3feeeb6f1fac {
href = "http://website.myxml.xsd"
}),
children = [
0;34#(Text "\n\t\t\t\t\t"),
0;34#(Element:0x3feeea7e8f88 {
name = "id",
namespace = 0;34#(Namespace:0x3feeeb6f1fac {
href = "http://website.myxml.xsd"
}),
children = [ 0;34#(Text "choice_5xBWm5NQRkA")]
}),
0;34#(Text "\n\t\t\t\t\t"),
0;34#(Element:0x3feeea7eb738 {
name = "description",
namespace = 0;34#(Namespace:0x3feeeb6f1fac {
href = "http://website.myxml.xsd"
}),
attributes = [
0;34#(Attr:0x3feeea7eb3f0 { name = "lang", value = "und" })],
children = [ 0;34#(Text "False")]
}),
0;34#(Text "\n\t\t\t\t")]
}),
0;34#(Text "\n\t\t\t")]
})
从这个Nokogiri :: XML :: Nodeset中提取这两个变量的最优雅方法是什么?
答案 0 :(得分:2)
假设您将已解析的输出存储在变量中,为此我将命名为@xml
。
@xml.css('component').map do |node|
{
id: node.children.css('id').first.text,
description: node.children.css('description').first.text
}
end
这应该为您提供包含所需数据的哈希数组。