Using [@attribute_name] we can select nodes that have the attribute irrespective of the value.
We can use any of the functions or combination of the functions such as starts-with and lowercase, for example, with this selector to suit our needs.
XML
<Galaxy>
<name>Milky Way</name>
<CelestialObject name="Earth" type="planet"/>
<CelestialObject name="Sun" type="star"/>
</Galaxy>
XPATH
/Galaxy/*[@name]
or
//*[@name]
OUTPUT
<CelestialObject name="Earth" type="planet" />
<CelestialObject name="Sun" type="star" />
XML
<Galaxy>
<name>Milky Way</name>
<CelestialObject name="Earth" type="planet"/>
<CelestialObject name="Sun" type="star"/>
</Galaxy>
XPATH
/Galaxy/*[@name='Sun']
or
//*[@name='Sun']
OUTPUT
<CelestialObject name="Sun" type="star" />
XML
<Galaxy>
<name>Milky Way</name>
<CelestialObject name="Earth" type="planet"/>
<CelestialObject name="Sun" type="star"/>
</Galaxy>
XPATH
/Galaxy/*[contains(@name,'Ear')]
or
//*[contains(@name,'Ear')]
Double quotes can also be used in place of single quotes:
/Galaxy/*[contains(@name, "Ear")]
OUTPUT
<CelestialObject name="Earth" type="planet" />
XML
<Galaxy>
<name>Milky Way</name>
<CelestialObject name="Earth" type="planet"/>
<CelestialObject name="Sun" type="star"/>
</Galaxy>
XPATH
/Galaxy/*[contains(lower-case(@name),'ear')]
or
//*[contains(lower-case(@name),'ear')]
or, with the string in double quotes:
//*[contains(lower-case(@name), "ear")]
OUTPUT
<CelestialObject name="Earth" type="planet" />
XML
<Galaxy>
<name>Milky Way</name>
<CelestialObject name="Earth" type="planet"/>
<CelestialObject name="Sun" type="star"/>
</Galaxy>
XPATH
/Galaxy/*[starts-with(lower-case(@name),'ear')]
or
//*[starts-with(lower-case(@name),'ear')]
OUTPUT
<CelestialObject name="Earth" type="planet" />
XML
<Galaxy>
<name>Milky Way</name>
<CelestialObject name="Earth" type="planet"/>
<CelestialObject name="Sun" type="star"/>
</Galaxy>
XPATH
/Galaxy/*[ends-with(lower-case(@type),'tar')]
or
//*[ends-with(lower-case(@type),'tar')]
OUTPUT
<CelestialObject name="Sun" type="star" />
Selector | function |
---|---|
@attribute_name | It selects the attribute value for a node, if present |