How can I get the value from an attribute using xmllint and XPath?

后端 未结 4 1411
小鲜肉
小鲜肉 2020-12-08 13:23

I want to get the value of name and put it in a variable using XMLLint





echo \'cat //body         


        
4条回答
  •  -上瘾入骨i
    2020-12-08 14:26

    An approach with a helper awk command that supports multiple attributes (a streamlined version of ego's approach):

    echo 'cat //*/@name' | xmllint --shell file | awk -F\" 'NR % 2 == 0 { print $2 }'
    

    The awk command:

    • splits xmllint's output lines into fields by " chars. (-F\")

      • Note that xmllint normalizes quoting around attribute values to "..." on output, even if the input had '...', so it's sufficient to split by ".
    • only processes even-numbered lines (NR %2 == 0), thereby filtering out the separator lines that cat invariably prints.

    • print $2 then prints only the 2nd field, which is the value of each attribute without the enclosing "...".

    Assuming the following sample XML in file:

    
      
      
    
    

    the above yields:

    abc
    def
    

提交回复
热议问题