Search code examples
xmlxpathxml-parsingxmllint

Extracting attributes from XML file using xmllint


This is a part of my XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<nlpcmp>
 <word string="getuserscount" occurrences="2">
  <systems>
   <system name="mks">
    <pos file="IrcChannel.cpp" part="adjective" line="414" occ="2"/>
   </system>
  </systems>
 </word>
 <word string="setuserprivilege" occurrences="2" >
  <systems>
   <system name="mks">
    <pos file="IrcChannel.cpp" part="adjective" line="375" occ="2"/>
   </system>
  </systems>
 </word>
 <word string="hasprivilege" occurrences="2" >
  <systems>
   <system name="mks">
    <pos file="IrcChannel.cpp" part="verb" line="360" occ="2"/>
   </system>
  </systems>
 </word>
 <word string="partmessage" occurrences="2" >
  <systems>
   <system name="TEST">
    <pos file="IrcChannel.cpp" part="verb" line="308" occ="2"/>
   </system>
  </systems>
 </word>
</nlpcmp>

I am trying to find the list of the strings for the systems that is called mks only using xmllint

The output should give me:

getuserscount
setuserprivilege
hasprivilege

so I tried this command:

xmllint --xpath 'string(//nlpcmp/word/@name)' file.xml

and there was no output, then I tried:

xmllint --xpath "//*[local-name()='word'][system/@name[mks]" file.xml

and it says : XPath error : Invalid predicate xmlXPathEval: evaluation failed

Then I tried

xmllint --xpath "//*[local-name()='word']" file.xml

and it gave me all the contents of the "word" tag, which I do not want. I only need the strings. How can I do that?


Solution

  • This xmllint command

    xmllint --xpath "/nlpcmp/word[systems/system/@name = 'mks']/@string" file.xml
    

    will yield this output

    getuserscount
    setuserprivilege
    hasprivilege
    

    as requested.