获取没有文本节点的元素的子元素

时间:2012-02-14 23:07:05

标签: ruby xml xpath nokogiri

我正在使用Nokogiri和Ruby来解释XML文件的内容。我希望在我的示例中获得所有元素的数组(或类似),这些元素是<where>的直接子元素。但是,我得到了各种文本节点(例如"\n\t\t\t"),这是我不想要的。有什么方法可以删除或忽略它们吗?

@body = "
<xml>
  <request>
    <where>
      <username compare='e'>Admin</username>
      <rank compare='gt'>5</rank>
    </where>
  </request>
</xml>" #in my code, the XML contains tab-indentation, rather than spaces. It is edited here for display purposes.

@noko = Nokogiri::XML(@body)
xml_request = @noko.xpath("//xml/request")
where = xml_request.xpath("where")
c = where.children
p c

上面的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

1 个答案:

答案 0 :(得分:14)

您(至少)有三个选项可供选择:

  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?)