从 unix 命令行进行基本 xml 解析的最简单方法 [英] Simplest way to do basic xml parsing from unix command line

查看:22
本文介绍了从 unix 命令行进行基本 xml 解析的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在搜索具有特定属性的 xml 文件.例如,包含以下模式的文件:

I'm searching for xml files that have certain properties. For example, files that contain the following pattern:

<param-value>
  <name>Hosts</name>
  <description>some description</description>
  <value></value>
</param-value>

对于这样的文件,我想解析另一个标签的值,比如:

For such files, I'd like to parse the value of another tag, such as:

<param-value>
  <name>Roles</name>
  <description>some description</description>
  <value>asdf</value>
</param-value>

并打印出文件名和asdf".从命令行完成此操作的最简单方法是什么?

And print out the file name along with "asdf". What's the simplest way to accomplish this from the command line?

我想到的一种方法是使用带有 -l 选项的 grep 来过滤匹配的文件,然后使用 xargs grep 提取 Roles 的值.但是,grep 不适用于多行正则表达式.我看到另一个问题表明它可以用 -Pzo 选项来完成,但没有任何运气让它在我的情况下工作.有没有更简单的方法?

One approach I was thinking of was just using grep with the -l option to filter the matching files out, and then using xargs grep to extract the value of Roles. However, grep doesn't work well with multi-line regexes. I saw another question that showed it could be done with the -Pzo options, but didn't have any luck getting it to work in my case. Is there a simpler approach?

推荐答案

以下 linux 命令使用 XPath 访问 XML 文件中的指定值

The following linux command uses XPath to access specified values within the XML file

for xml in `find . -name "*.xml"`
do  
echo $xml `xmllint --xpath "/param-value/value/text()" $xml`| awk 'NF>1'
done

匹配 XML 文件的示例输出:

Example output for matching XML files:

./test1.xml asdf
./test4.xml 1234

这篇关于从 unix 命令行进行基本 xml 解析的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆