Hello,
I’ve just been playing around with IronRuby and processing some XML
from a REST service. I’ve created this wrapper:
require ‘mscorlib’
require ‘System, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089’
include System
require ‘System.Xml, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089’
include System::Xml
#Wrapper around .Net XMLDocument to make it easier to query with -
more like REXML
class Document
def initialize(xml)
@document = XmlDocument.new
@document.load_xml xml
end
def get(xpath) #.collect - I want to pass the block in, not have
to use it on the outside.
@document.SelectNodes(xpath)
end
end
class XmlNodeList
def get(name)
list.select {|e| e.Name == name}
end
end
class XmlElement
def get(name)
if has_attribute name
get_attribute name
else
get_elements_by_tag_name name
end
end
def text
inner_text
end
end
My first problem is that I’m getting XmlElement object instead of
XmlNode from an XmlNodeList. If I had XmlNode, then I could do
e[‘n’].text - which is what I want. As a result, my code to access
the N element looks like this:
require ‘xml’
@document = Document.new(‘testaaa’)
@document.get(‘x’).collect {|n| puts n.text}
testaaa
@document.get(‘x/x1’).collect {|e| e.get(‘n’).collect {|n| puts n.text}}
test
Why am I getting a XmlElement object? How can I access my xml in a
cleaner fashion?
My second problem, I wanted to be able to pass in a block
def get(xpath)
@document.SelectNodes(xpath).collect {yield}
end
In this case, I get the following error:
@document.get(‘x’) {|n| puts n.text}
:1: undefined methodtext' for nil:NilClass (NoMethodError) from xml.rb:27:in
get’
I changed it to {|n| yield}, but I get the same error. The object is
always nil. What am I doing wrong?
Hope this all makes sense.
Thanks
Ben