skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    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?


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

    //*[@ref]/name()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search