From: "Kyle X." Date: 2011-04-12T03:57:42+09:00 Subject: Re: Can you search in REXML by attributes? > This works for me: > > $ cat noko.rb && ruby -rubygems noko.rb > require 'nokogiri' > > doc = Nokogiri::XML(File.read("one.xml")) > reference = doc.css("IfcCartesianPoint Coordinates > IfcLengthMeasure").first > puts reference.text > > 117.4 > > But if I leave a space before IfcCartesianPoint in the call to the css > method I get a parser error (`on_error': unexpected ' ' after '' > (Nokogiri::CSS::SyntaxError)). This is my file one.xml: > > > > > > > > > > > > > > > > > 117.4 > 119.7 > 0. > > > > > This works too: > > doc.css("IfcCartesianPoint Coordinates IfcLengthMeasure").each {|el| > puts el.text} > > Produces: > > 117.4 > 119.7 > 0. Thank you for your reply. When I continue to try and read the file I have it keeps returning nil values and thus doesn't work. But when I copy and paste the xml you have written over the file I am trying to read then it does work. I understand that the path is slightly different but using the xpath command- doc.xpath("//IfcCartesianPoint/Coordinates/IfcLengthMeasure").each {|el| puts el.text} It should skip ahead to the first appearance of IfcCartesianPoint, much the same as it works for using REXML xpath, no? As this same sting of IfcCartesianPoint/Coordinates/IfcLengthMeasure appears in this file. Based on the documentation here - (http://nokogiri.org/tutorials/searching_a_xml_html_document.html) I think it should be working but it always returns nil. I have attached the xml file I am trying to read and was wondering if you could see where my error is occurring. The first instance of IfcCartesianPoint/Coordinates/IfcLengthMeasure appears on line 225. > > Maybe it's the way you are passing the file to Nokogiri::XML? By the > way, in your way you are not closing the file handler. If you want to > pass Nokogiri the file instead of reading it yourself you can do: > > doc = nil > File.open("one.xml") {|f| doc = Nokogiri::XML(f)} > > or > > doc = File.open("one.xml") {|f| Nokogiri::XML(f)} > > This way, the file is properly closed. > > Jesus. Is there an advantage to using .open vs .read? The program I am writing has to grab lots of information from the xml, maybe 300 items, would it make a difference in speed to use one vs the other? Also for me to read a file at say c:\one.xml for it to read I have to write - doc = File.open("/one.xml") {|f| Nokogiri::XML(f)} Another form will not read including "\one.xml" Thank you again for your time, you have been most helpful and it is greatly appreciated. Attachments: http://www.ruby-forum.com/attachment/6114/one.xml -- Posted via http://www.ruby-forum.com/.