how to read xml file in linux

巧了我就是萌 提交于 2019-12-08 12:09:06

问题


I have one xml file as below, I need "en" using some unix command.

        <void method="put">
            <string>LANGUAGE</string>
            <string>en</string>
        </void>    

using below command (got from some link in google),

sed -n '/string/{s/.*<string>//;s/<\/string.*//;p;}' Locale.xml

I am getting output as

LANGUAGE
en

so I used

sed -n '/string/{s/.*<string>//;s/<\/string.*//;p;}' Locale.xml | tail -1

But is there any option in sed by which I can get second value only?


回答1:


You can use this sed,

sed -n '/LANGUAGE/{N; s/.*<string>\(.*\)<\/string>.*/\1/p; }' Locale.xml



回答2:


Use xmlstarlet.

$ cat x.xml 
<?xml version="1.0"?>
<void method="put">
  <string>LANGUAGE</string>
  <string>en</string>
</void>
$ xmlstarlet sel -t -c '/void/string[2]/text()' x.xml
en

Or use xmllint.

$ xmllint --xpath '/void/string[2]/text()' x.xml
en

More about XPath.




回答3:


You can search for LANGUAGE and the print next line:

awk -F"[<>]" '/LANGUAGE/ {getline;print $3}' Locale.xml 
en

Or search for string and print the last one:

awk -F"[<>]" '/string/ {f=$3} END {print f}' Locale.xml
en



回答4:


Using xsh:

open file.xml ;
echo //void[string="LANGUAGE"]/string[2]


来源:https://stackoverflow.com/questions/23341361/how-to-read-xml-file-in-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!