我有以下XML:除了實際元素之外,Nokogiri XML.children還返回格式化元素。如何避免這種情況?
<attributes>
<intelligence>27</intelligence>
<memory>21</memory>
<charisma>17</charisma>
<perception>17</perception>
<willpower>17</willpower>
</attributes>
我想分析如下:
intelligence: 27, memory: 21, charisma: 17, perception: 17, willpower: 17
當我嘗試此代碼:
def get_attributes(api)
attributes = []
api.xpath("//attributes").children.each do |attribute|
name = attribute.name.tr('^A-Za-z0-9', '')
text = attribute.text
attributes << "#{name}: #{text}"
end
attributes
end
我與新行數據結果(因爲的格式):每個偶數小孩:
#(Text "\n ")
#(Element:0x3ffe166fdb9c { name = "intelligence", children = [ #(Text "20")] })
#(Text "\n ")
#(Element:0x3ffe166f71ac { name = "memory", children = [ #(Text "25")] })
#(Text "\n ")
#(Element:0x3ffe166f3818 { name = "charisma", children = [ #(Text "23")] })
#(Text "\n ")
#(Element:0x3ffe166f0604 { name = "perception", children = [ #(Text "16")] })
#(Text "\n ")
#(Element:0x3ffe166b52e8 { name = "willpower", children = [ #(Text "15")] })
#(Text "\n ")
Nokogiri中有沒有一種方法可以跳過這些「僅格式化」的孩子?還是我必須手動遍歷奇數編號的元素?
我希望api.xpath("//attributes").children
導航實際的孩子,而不是格式文本。
Xpath FTW。我知道有更好的辦法... – 2013-02-28 16:52:49