在 RubyMine 中处理 XML

Processing XML in RubyMine

我正在尝试在 Ruby 我的 XML 中学习处理,基于 nokogiri.com 上的教程以及我在 whosebug.com 上搜索论坛的内容.

我的代码是:

Then /^I process an XML file:(.*?).$/ do |arg1|
  xml_str = Nokogiri::XML('<root>
  <sitcoms>
    <sitcom>
      <name>Married with Children</name>
      <characters>
        <character>Al Bundy</character>
        <character>Bud Bundy</character>
        <character>Marcy Darcy</character>
      </characters>
    </sitcom>
    <sitcom>
      <name>Perfect Strangers</name>
      <characters>
        <character>Larry Appleton</character>
        <character>Balki Bartokomous</character>
      </characters>
    </sitcom>
  </sitcoms>
  <dramas>
    <drama>
      <name>The A-Team</name>
      <characters>
        <character>John "Hannibal" Smith</character>
        <character>Templeton "Face" Peck</character>
        <character>"B.A." Baracus</character>
        <character>"Howling Mad" Murdock</character>
      </characters>
    </drama>
  </dramas>
</root>
')

  doc  = Nokogiri::XML(xml_str)
  sleep 2
  puts "\ndoc class is " + doc.class.to_s
  sleep 2

  thing = doc.xpath("//character")
  sleep 2
  puts "\nthing class is " + thing.class.to_s
  sleep 2

  stop_value = thing.length
  idx = 0
  puts "\nthing length is #{stop_value}"
  if thing.empty?
    puts "\nthing is empty"
  else
    pits "\nthing is NOT empty"
  end

  while idx < stop_value
    puts "\n" + thing[idx].to_s
    idx += 1
  end

"doc" 的 class 是正确的,但是 "thing" 的 class 是 Nil。

我是 运行 Ruby我的 8.0.3、Ruby 2.2.1 和 Appium 1.5.3。

提前致谢。

问题是您调用了 Nokogiri::XML 两次:一次在第 2 行,您将结果分配给 xml_str,然后在您调用 doc = Nokogiri::XML(xml_str) 时再次调用。如果您将代码更改为只调用一次,它可以正常工作:

doc = Nokogiri::XML('<root>
  <sitcoms>
    <sitcom>
      <name>Married with Children</name>
      <characters>
        <character>Al Bundy</character>
        <character>Bud Bundy</character>
        <character>Marcy Darcy</character>
      </characters>
    </sitcom>
    <sitcom>
      <name>Perfect Strangers</name>
      <characters>
        <character>Larry Appleton</character>
        <character>Balki Bartokomous</character>
      </characters>
    </sitcom>
  </sitcoms>
  <dramas>
    <drama>
      <name>The A-Team</name>
      <characters>
        <character>John "Hannibal" Smith</character>
        <character>Templeton "Face" Peck</character>
        <character>"B.A." Baracus</character>
        <character>"Howling Mad" Murdock</character>
      </characters>
    </drama>
  </dramas>
</root>
')

puts "doc class is #{doc.class}"
# => doc class is Nokogiri::XML::Document

thing = doc.xpath("//character")
puts "thing class is #{characters.class}"
# => thing class is Nokogiri::XML::NodeSet