Search code examples
xmlxml-parsingxmlstarlet

xmlstarlet not working for simple selection based on child string value


I am working on XML file like

<bookstore> 
   <book category="cooking"> 
       <title lang="en">Everyday Italian</title> 
       <author>adc</author> 
       <year>2005</year> 
       <price>30.00</price> </book> 
   <book category="children"> 
       <title lang="en">Harry Potter</title> 
       <author>xyz</author> 
       <year>2005</year> 
       <price>29.99</price> </book> 
</bookstore>

Using xmlstarlet on linux

xmlstarlet sel -t -m 'bookstore/author [1]' -n books.xml 

Would give output as "adc", but how can I find the field when I already know the value?

Like I know author tag has value "adc". How should I find bookstore/author [x] the x?


Solution

  • After a bit of searching I found the answer and leaving it in someone else stumbles across same

    To select value by field in xmlstarlet use

    xmlstarlet -t -c 'bookstore/book[author="adc"]' -n books.xml
    

    Here bookstore/book is complete path of node which contains author [author=value] is used to select nodes only where author has specific value And books.xml is your xml file

    I am sure others can explain better but hope you find this of some help