简体   繁体   中英

Accessing XPath query results when all that is returned is a LibXML object in Ruby

require 'net/http'; require 'libxml'

data = Net::HTTP.get_response(URI.parse('http://myurl.com')).body
source = LibXML::XML::Parser.string(data).parse

tables = source.find('//table')

returns

 => #<LibXML::XML::XPath::Object:0x1f4f50>

How do I access this? There are at least 11 tables there.

ps I can't use Nokogiri on my current setup.

You access the XPath results by asking for the node item like this.

require 'net/http'
require 'libxml'

# Sample text with a few tables
xml=<<END
<html>
  <table id="t1"><tr><td>foo</td></tr></table>
  <table id="t2"><tr><td>goo</td></tr></table>
  <table id="t3"><tr><td>hoo</td></tr></table>
</html>
END

# Parse the text into tables
source = LibXML::XML::Parser.string(xml).parse
tables = source.find('//table')

# The XPath #each iterator does each XML node
tables.each {|node|
  puts node["id"] 
}

If you have an older version of libxml:

- puts node["id"] 
+ puts node.property("id")

设法解决与Hpricot!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM