问题描述
我正在尝试从pom.xml中提取节点的值:
I'm trying to extract the value of a node from a pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project>
<parent>
<groupId>org.me.labs</groupId>
<artifactId>my-random-project</artifactId>
<version>1.5.0</version>
</parent>
...
</project>
我需要使用shell命令从XML中提取artifactId和版本.我有以下要求/注意事项:
I need to extract the artifactId and version from the XML using a shell command. I have the following requirements/observations:
- shell脚本将在我们使用的构建程序集文件中完成,因此脚本越小越好.
- 由于它将在多个系统(通常是RHEL5)上使用,因此我正在寻找可以在默认图像上本机运行的东西.
- 类似的标签可以出现在pom的其他位置,所以我不能简单地awk这些标签.
我尝试了以下操作:
-
xpath
在我的Mac上可用,但默认情况下在RHEL计算机上不可用.同样,对于xmllint --xpath
,我猜它只能在xmllint
的更高版本中使用,而我没有也不能执行. -
xmllint --pattern
似乎很有希望,但我似乎无法从xmllint --pattern '//project/parent/version' pom.xml
(打印整个XML)或xmllint --stream --pattern '//project/parent/version' pom.xml
(无输出)中得到输出.
xpath
works on my Mac, but isn't available by default on RHEL machines. Similarly forxmllint --xpath
, which I guess is only available on later versions ofxmllint
, which I don't have and can't enforce.xmllint --pattern
seemed promising, but I can't seem to get an output out ofxmllint --pattern '//project/parent/version' pom.xml
(prints entire XML) orxmllint --stream --pattern '//project/parent/version' pom.xml
(no output).
我意识到这是SO上的一个常见问题,但是以上几点是为什么我不能使用这些答案的原因. TIA为您提供帮助.
I realize this is a common question here on SO, but the points above are why I can't use those answers. TIA for your help.
推荐答案
我已经设法使用xmllint --shell
这个相当不明智的脚本暂时解决了该问题.
I've managed to solve it for the time being with this rather unwiedly script using xmllint --shell
.
echo "cat //project/parent/version" | xmllint --shell pom.xml | sed '/^\/ >/d' | sed 's/<[^>]*.//g'
如果XML节点具有像我的pom.xml一样的名称空间属性,事情就会变得很重,基本上是按名称提取节点:
If the XML nodes have namespace attributes like my pom.xml had, things get heavier, basically extracting the node by name:
echo "cat //*[local-name()='project']/*[local-name()='parent']/*[local-name()='version']" | xmllint --shell pom.xml | sed '/^\/ >/d' | sed 's/<[^>]*.//g'
希望它会有所帮助.如果有人能简单地表达这些观点,我将不胜感激.
Hope it helps. If anyone can simply these expressions, I'd be grateful.
这篇关于设置本机外壳命令以从XML提取节点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!