Use XPath to select root and children matching expression
Asked Answered
S

2

2

I'm using Nokogiri to parse some XML that looks kind of like:

<item name="item one">
    <other name="other name"/>
    <third />
</item>
<item name="item two">
    <other />
    <third />
</item>

I'm parsing over the items using Nokogiri like so:

xmldoc.xpath("//item").each do |node|
  node.xpath("//*[@name]") # Gives me *all* elements in the doc
  node.xpath(".//*[@name]") # Gives me child elements of the item
end

What expression can I use to get [item, other] from the first node as I iterate through?

Semipermeable answered 4/4, 2016 at 20:14 Comment(1)
Please read "minimal reproducible example". Your XML is not valid and your source code doesn't run. Don't ask us to write code just to test yours.Divided
B
2

The . at the beginning would make the XPath expression context-specific, use @ to get the attributes, @* to get all attributes (wildcard):

node.xpath(".//*/@*")
node.xpath("@*")

And, getting all attributes of the current node as well as all attributes of all child nodes:

node.xpath(".//@*")
Bestride answered 4/4, 2016 at 20:23 Comment(4)
Is there one expression that would accomplish both lines at the same time? I want all attributes on the root or any child.Semipermeable
How would I modify it to get just all "name" attributes (ignoring other attributes)?Semipermeable
@Semipermeable try ./descendant-or-self::node()/@name.Bestride
.//@name will work as well. // is shorthand for /descendant-or-self::node()/.Rosary
J
0

i don't know if it will work for you, but if you find nodes you can use node.name to get item element, you can find all other and check if .parent.name== 'item' see more here: https://github.com/sparklemotion/nokogiri/wiki/Cheat-sheet

Japeth answered 19/4, 2016 at 12:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.