我试图从这个XML中检索两小段信息。id
(choice_xxxxxx)和description
(真/假):
<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 "ntttt"),
0;34#(Element:0x3feeea7e36b4 {
name = "component",
namespace = 0;34#(Namespace:0x3feeeb6f1fac {
href = "http://website.myxml.xsd"
}),
children = [
0;34#(Text "nttttt"),
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 "nttttt"),
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 "ntttt")]
}),
0;34#(Text "ntttt"),
0;34#(Element:0x3feeea7ea34c {
name = "component",
namespace = 0;34#(Namespace:0x3feeeb6f1fac {
href = "http://website.myxml.xsd"
}),
children = [
0;34#(Text "nttttt"),
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 "nttttt"),
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 "ntttt")]
}),
0;34#(Text "nttt")]
})
从Nokogiri::XML::Nodeset中提取这两个变量的最优雅的方法是什么?
前提是您将解析的输出存储在一个变量中,为此我将@xml
命名为 .
@xml.css('component').map do |node|
{
id: node.children.css('id').first.text,
description: node.children.css('description').first.text
}
end
这应该为您提供一个包含所需数据的哈希数组。