What's the xpath syntax to get tag names?

流过昼夜 提交于 2019-12-06 19:06:32

问题


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

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