Rectangle 27 0

ruby How to access attributes using Nokogiri?


xml.xpath("//Placement").attr("messageId")

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):

Note
Rectangle 27 0

ruby How to access attributes using Nokogiri?


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
nokogiri_element.xpath("@id").text()
reader = Nokogiri::XML::Reader(builder.to_xml)
reader.read #Moves to next node in document
reader.attribute("messageId")

I looked @ this code dzone.com/snippets/finding-elements-attributes and was breaking my head because I was using the @ outside [. This has been a real saviour. I have wasted 2 days to figure out a way to parse xml attributes and this is a true saviour. It will be nice if this link added to nokogiri

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.

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).

What you probably want to do is use Nokogiri::XML::Document if you want to search an XML document by attribute.

Note
Rectangle 27 0

ruby How to access attributes using Nokogiri?


xml.xpath("//Placement").attr("messageId")

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):

Note