Use XPath to select root and children matching expression

ぐ巨炮叔叔 提交于 2020-01-06 02:27:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!