I have a simple task of accessing the values of some attributes. This is a simple script that uses Nokogiri::XML::Builder
to create a simple XML doc.
Using Nokogiri::XML::Reader works for your example, but probably isn't the full answer you are looking for (Note that there is no attributes method for Builder).
reader = Nokogiri::XML::Reader(builder.to_xml)
reader.read #Moves to next node in document
reader.attribute("messageId")
Note that if you issued reader.read
again and then tried reader.attribute("messageId")
the result will be nil
since the current node will not have this attribute.
What you probably want to do is use Nokogiri::XML::Document if you want to search an XML document by attribute.
doc = Nokogiri::XML(builder.to_xml)
elems = doc.xpath("//*[@messageId]") #get all elements with an attribute of 'messageId'
elems[0].attr('messageId') #gets value of attribute of first elem
Here is a slightly more succinct way to access attributes using Nokogiri
(assuming you already have your xml stored in a variable called xml
, as covered by @atomicules' answer):
xml.xpath("//Placement").attr("messageId")