Search code examples
xmlbashterminalxmlstarletxmllint

Search and return tag name based off attribute within the tag xml bash


I have a tag which contains a "name" attribute. The tag (xsd:tag1) itself is not unique within the XML file but the name attribute (name1) is unique. How can I search and return the tag name (i.e. to return xsd:tag1) using xmlstarlet or otherwise? An example of the XML is shown below.

<doc xmlns:xsd="http://example.com">
   <xsd:parentTag>
      <xsd:tag1 name="name1" />
   </xsd:parentTag>
</doc>

Solution

  • The example input you provide has two problems:

    • <xsd:tag1 name="name1"> has to be closed
    • The namespace prefix xsd: has to be defined

    If the file input.xml is as follows:

    <doc xmlns:xsd="http://example.com">
     <xsd:parentTag>
      <xsd:tag1 name="name1" />
     </xsd:parentTag>
    </doc>
    

    the following command

    xmlstarlet sel -T -t -m "//*[@name='name1']" -v 'name()' input.xml
    

    yields

    xsd:tag1
    

    The trick is to have a correct xmlns declaration in the input, in order to avoid xmlstarlet complain about undefined namespaces.