问题
I'm using Nokogiri to parse a large XML file. Say I've got the following structure:
<menagerie>
<penguin>Pablo</penguin>
<penguin>Mortimer</penguin>
<bull>Ferdinand</bull>
<aardvark>James Cornelius Madison Humphrey Zophar Handlebrush III</aardvark>
</menagerie>
I can count the non-penguins like this:
xml.xpath('//menagerie//*[not(penguin)]').length // 2
But how do I get a list of the tags, like this? (The exact format isn't important; I just want to visually scan the non-penguins.)
bull
aardvark
Update
This gave me the list I wanted - thanks Oded and TMN and delnan!
xml.xpath('//menageries/*[not(penguin)]').each do |node|
puts node.name()
end
回答1:
You can use the name() or local-name() XPath function.
See the examples on zvon.
回答2:
I know it's a bit outdated but you should do: xml.xpath('//meagerie/*[not(penguin)]/name()')
as the expression. Note the slash, not the dot. This is how you call methods on the current node in XPath.
来源:https://stackoverflow.com/questions/4727610/whats-the-xpath-syntax-to-get-tag-names