问题
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?
回答1:
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(".//@*")
回答2:
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
来源:https://stackoverflow.com/questions/36412067/use-xpath-to-select-root-and-children-matching-expression