简体   繁体   English

Shell 脚本获取 XML 标记的值

[英]Shell scripting get value of XML tags

I have the XML data below.我有下面的 XML 数据。

<java:Parameter>
       <java:Name>flagCount</java:Name>
       <java:Value>Y</java:Value>
</java:Parameter>
<java:Parameter>
       <java:Name>returnCode</java:Name>
       <java:Value>001</java:Value>
</java:Parameter>

I want to get only Value of Name "returnCode" (Value is 001).我只想获得名称“returnCode”的值(值为 001)。

I try to do by command below, but does't work.我尝试通过下面的命令来做,但不起作用。

echo -e 'cat //java:Value/text()' | xmllint --shell test_check_main.xml

XPath error : Undefined namespace prefix
xmlXPathEval: evaluation failed
//java:Value/text(): no such node

How to implement by shell scripting?如何通过shell脚本实现?

First fix the xml:首先修复xml:

xml=$( cat <<'EOF'
<java:Parameter>
   <java:Name>flagCount</java:Name>
   <java:Value>Y</java:Value>
</java:Parameter>
<java:Parameter>
   <java:Name>returnCode</java:Name>
   <java:Value>001</java:Value>
</java:Parameter>
EOF
)
xml2="<java:root xmlns:java=\"http://fakens.com\">""$xml""</java:root>"

Then you can get it with this xpath statement:然后你可以用这个 xpath 语句得到它:

echo "$xml2" | xmllint --xpath '//*[local-name()="Parameter"]/*[local-name()="Name" and contains(text(),"returnCode")]/parent::*[namespace-uri()="http://fakens.com"]/*[local-name()="Value"]/text()' -

It is a bit round-about and annoying, but it is correct.这有点迂回和烦人,但它是正确的。

I hope this helps you :)我希望这可以帮助你 :)

cat yourXML.xml | grep -A 1 'returnCode' | tail -1 | grep -oP '(?<=<java:Value>).*' | cut -d '<' -f1

There can be multiple ways of doing this but currently i came up with this one.可以有多种方法来做到这一点,但目前我想出了这个。

another way...其它的办法...

grep returnCode file -A1 | grep 返回代码文件 -A1 | tail -1 |尾-1 | cut -d\\< -f2 |剪切 -d\\< -f2 | cut -d> -f2剪切 -d> -f2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM