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>
The example input you provide has two problems:
<xsd:tag1 name="name1">
has to be closedxsd:
has to be definedIf 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.