【问题标题】:How to get a tag value from an XML in string如何从字符串中的 XML 获取标记值
【发布时间】:2020-08-20 21:40:50
【问题描述】:

我声明了以下变量

TEXT='<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://ws.chpconsulting.com/alfa/requestcontext/v1" xmlns:v11="http://ws.chpconsulting.com/alfa/user/v1"><soapenv:Header><v1:context></v1:context></soapenv:Header><soapenv:Body><v11:load><!--Optional:--><userId>IN2Z83</userId></v11:load></soapenv:Body></soapenv:Envelope>'

如何在shell脚本中获取userID标签值

【问题讨论】:

标签: xml shell awk sed


【解决方案1】:

试试这个

 grep -o 'userId>.*</userId' | sed 's/^.*>//g;s/<.*$//g'

演示:

$echo $TEXT
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://ws.chpconsulting.com/alfa/requestcontext/v1" xmlns:v11="http://ws.chpconsulting.com/alfa/user/v1"><soapenv:Header><v1:context></v1:context></soapenv:Header><soapenv:Body><v11:load><!--Optional:--><userId>IN2Z83</userId></v11:load></soapenv:Body></soapenv:Envelope>
$echo $TEXT | grep -o 'userId>.*</userId' | sed 's/^.*>//g;s/<.*$//g'
IN2Z83
$

【讨论】:

    【解决方案2】:

    假设您使用像 bash 这样可以理解 here string 语法的 shell,您可以使用像 xmlstarlet 这样的命令行 XML 工具:

    xmlstarlet sel -t -v '//userId' <<< "$TEXT"
    

    或来自 W3C 的 HTML-XML-Utils 包的 hxselect

    hxselect -c userId <<< "$TEXT"
    

    或您选择的其他工具。

    否则,您可以将 XML 文本通过管道传输到工具:

    echo "$TEXT" | xmlstarlet sel -t -v '//userId'
    

    【讨论】:

      猜你喜欢
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-30
      相关资源
      最近更新 更多