Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Finding Elements By Attributes With Nokogiri

DZone's Guide to

Finding Elements By Attributes With Nokogiri

·
Free Resource
To find elements by attribute with nokogiri, no matter where the element/attribute is, use these:


@doc = Nokogiri::XML(File.open("myFile.xml").read)
# get elements with attribute:
elements = @doc.xpath("//*[@*[attribute_name]]")
# get just the attribute:
attributes = @doc.xpath("//@*[attribute_name]")


If you want them with a specific namespace, do this:


# get elements with attributes from a given namespace:
elements = @doc.xpath("//*[@*[namespace-uri()='http://foo.example.com']]")
# get attributes from a given namespace:
attributes = @doc.xpath("//@*[namespace-uri()='http://foo.example.com']")
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}