Search code examples
xmlxpathxmllint

Extracting single value from XML array


I have the following XML:

<computer>
<extension_attributes>
    <extension_attribute>
      <id>22</id>
      <name>aname</name>
      <type>String</type>
      <multi_value>false</multi_value>
      <value>auidhg</value>
    </extension_attribute>
    <extension_attribute>
      <id>23</id>
      <name>ap</name>
      <type>String</type>
      <multi_value>false</multi_value>
      <value>d3HtVD</value>
    </extension_attribute>
</extension_attributes>
</computer>

I want to extract the value for the extension attribute item with the name "aname" (i.e. I want the value auidhg). I'm wondering if there is an Xpath statement I can use with xmllint?


Solution

  • This should be easy using a predicate to select the right extension_attribute.

    This XPath:

    //extension_attribute[name='aname']/value
    

    returns:

    <value>auidhg</value>
    

    If you just want the text value, you can select the text node...

    //extension_attribute[name='aname']/value/text()
    

    or use string() or normalize-space()...

    normalize-space(//extension_attribute[name='aname']/value)
    

    any of these return:

    auidhg
    

    See my links above for more details on the string() and normalize-space() functions and when they might be preferable to just selecting text().