InQusitive InQusitive - 6 months ago 19
Ruby Question

How to do nokogiri attribute selection?

I have many statements like this in my test.xml file

<House name="bla"><Room id="bla" name="black" ></Room></House>

How do I print all Rooms with
. I am using CSS selector but Only
attributes are taken by the selector.

I started with trying to print all name's, doesn't matter House or Room.

nodes = doc.css("name")
. But it gives null as the output. So I am not able to proceed.


In CSS you have a syntax for matching elements by an attribute key-val pair:

nodes = doc.css("[name='black']")

For future reference you can also chain attribute selectors

nodes = doc.css(".my-class[name='black'][foo='bar']")

Or omit the val and match any element where the attribute is present:

nodes = doc.css("[name]")