Search code examples
xmllint

XMLLINT get first matching child element


Given xml

<parent>
   <child> test1 </child>
   <child> test2 </child>
</parent>

Using xmllint I can get the childs with:

| xmllint --format --xpath '//parent/child/text()' -   

This returns all child texts

 test1 test2

However I only want to get the first/or second child content. How can one select the needed child position?


Solution

  • Specifying the position as

    //parent/child[1]/text()
    //parent/child[2]/text()
    

    or

    cat tmp2.xml | xmllint --xpath '(//parent/child/text())[1]' -
    cat tmp2.xml | xmllint --xpath '(//parent/child/text())[2]' -