2012-02-14 137 views
6

我正在使用Nokogiri和Ruby來解釋XML文件的內容。我想在我的示例中獲得所有元素的數組(或類似),這些元素是<where>的直接子元素。但是,我收到了各種不同的文本節點(例如"\n\t\t\t"),這是我不想要的。有什麼方法可以刪除或忽略它們嗎?獲取沒有文本節點的元素的子元素

以上Ruby腳本輸出:

[#<Nokogiri::XML::Text:0x100344c "\n\t\t\t">, #<Nokogiri::XML::Element:0x1003350 name="username" attributes=[#<Nokogiri::XML::Attr:0x10032fc name="compare" value="e">] children=[#<Nokogiri::XML::Text:0x1007580 "Admin">]>, #<Nokogiri::XML::Text:0x100734c "\n\t\t\t">, #<Nokogiri::XML::Element:0x100722c name="rank" attributes=[#<Nokogiri::XML::Attr:0x10071d8 name="compare" value="gt">] children=[#<Nokogiri::XML::Text:0x1006cec "5">]>, #<Nokogiri::XML::Text:0x10068a8 "\n\t\t">]

我想以某種方式獲得下列對象:

[#<Nokogiri::XML::Element:0x1003350 name="username" attributes=[#<Nokogiri::XML::Attr:0x10032fc name="compare" value="e">] children=[#<Nokogiri::XML::Text:0x1007580 "Admin">]>, #Nokogiri::XML::Element:0x100722c name="rank" attributes=[#<Nokogiri::XML::Attr:0x10071d8 name="compare" value="gt">] children=[#<Nokogiri::XML::Text:0x1006cec "5">]>]

目前,我可以解決使用

問題
c.each{|child| 
    if !child.text? 
    ... 
    end 
} 

但是c.length == 5。這將讓我的生活更容易,如果有人可以建議如何排除C直接子文本節點,讓c.length == 2

回答

10

你(至少)三個選項可供選擇:

  1. 使用c = where.element_children代替的c = where.children

  2. 只選擇直接的子元素:
    c = xml_request.xpath('./where/*')
    c = where.xpath('./*')

  3. 過濾兒童的名單only those that are elements
    c = where.children.select(&:element?)

+0

感謝。選項2似乎是完美的。 – SimonMayer 2012-02-14 23:48:04

相關問題