Home > Software design >  Retrieving the node names of all the xml elements with specific attribute name
Retrieving the node names of all the xml elements with specific attribute name

Time:02-23

I have an xml, let's call it example.xml that looks like this:

<a>
  <b ref="lala">text of node b
  </b>
  <c ref="hihi">text of node c
  </c>
  <d somethingelse="foo">text of the node d
  </d>
</a>

I want to get the names of all the nodes that have an attribute called "ref"

so my output would be:

b
c

I have tried: xmlstarlet sel -t -v "name(//*[@ref])" example.xml but I only get the name of the first node as an output i.e., b. What is missing in my command to get all the node names?

Note: I run on debian bulleyes and here is my xmlstarlet version:

xmlstarlet --version
1.6.1
compiled against libxml2 2.9.10, linked with 20910
compiled against libxslt 1.1.34, linked with 10134

CodePudding user response:

Found something that seems to work:

xmlstarlet sel -t -m "//*[@ref]" -v "name()" -n example.xml

The -n is the tag to give the output on different lines.

It might have been a problem of version (not sure). Anyway this post about unique vs multiple output with xmlstarlet gave me some help:

Why doesn't xmlstarlet select all nodes?

CodePudding user response:

Try this one to get names of nodes with "ref" attribute:

//*[@ref]/name()
  • Related