Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the xpath syntax to get tag names?

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
like image 460
Nathan Long Avatar asked Jan 18 '11 18:01

Nathan Long


2 Answers

You can use the name() or local-name() XPath function.

See the examples on zvon.

like image 91
Oded Avatar answered Nov 16 '22 00:11

Oded


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.

like image 37
bogdan.mustiata Avatar answered Nov 16 '22 01:11

bogdan.mustiata