我使用Nokogiri来解析一些看似类似的XML:
<item name="item one">
<other name="other name"/>
<third />
</item>
<item name="item two">
<other />
<third />
</item>
我正在使用Nokogiri解析项目,如下所示:
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
当我迭代时,我可以使用什么表达式从第一个节点获取[item, other]
?
答案 0 :(得分:2)
开头的.
会使XPath表达式特定于上下文,使用@
获取属性,@*
获取所有属性(通配符):
node.xpath(".//*/@*")
node.xpath("@*")
并获取当前节点的所有属性以及所有子节点的所有属性:
node.xpath(".//@*")
答案 1 :(得分:0)
我不知道它是否适合您,但如果您找到节点
您可以使用item
获取other
元素,您可以找到所有.parent.name== 'item'
并检查是否json_text = json_file.read().replace('var abc=','')
json_data = json.dumps(json_text)
pprint(json_data)
在这里看到更多:
https://github.com/sparklemotion/nokogiri/wiki/Cheat-sheet