DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Lance has posted 24 posts at DZone. View Full User Profile

Finding Elements By Attributes With Nokogiri

  • submit to reddit
        To find elements by attribute with nokogiri, no matter where the element/attribute is, use these:

@doc = Nokogiri::XML("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()='']]")
# get attributes from a given namespace:
attributes = @doc.xpath("//@*[namespace-uri()='']")