带有XPATH的Linux Bash XMLLINT [英] Linux Bash XMLLINT with XPATH
问题描述
今天,我开始学习如何正确使用xmllint.它似乎没有被很好地覆盖或解释.我计划使用一个语言资源文件来运行我的整个系统.我混合了bash脚本和php页面,必须从该语言文件中读取.
Today I get to learn how to use xmllint properly. It does not seem to be well covered or explained. I plan to use a single language resource file to run my entire system. I have a mixture of bash scripts and php pages that must read from this language file.
当前,我在xml文件en.xml中使用以下格式:
Currently I am using the following format in my xml file en.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item id="index.php">
<label>LABEL</label>
<value>VALUE</value>
<description>DESCRIPTION</description>
</item>
<item id="config.php">
<label>LABEL</label>
<value>VALUE</value>
<description>DESCRIPTION</description>
</item>
</resources>
现在,我需要从bash脚本行开始,该行应从xml文件中提取数据值.例如,我想从index.php
项目中获取DESCRIPTION
的值.
Now I need to start with a bash script line that should pull the data values from the xml file. For example I want to get the value of DESCRIPTION
from the index.php
item.
我正在使用
xmllint --xpath 'string(//description)' /path/en.xml
对于可以使用的其他布局,但是现在我更改了xml文件的布局,我迷失了如何最好地定位特定的<item>
,然后在bash脚本中向下钻取其子元素.
for a different layout which worked, but now that I am changing the layout of my xml file, I am lost as to how best to target a specific <item>
and then drill down to its child element in the bash script.
有人可以帮助xmllint --xpath
行获得此值吗?
Can someone help with a xmllint --xpath
line to get this value please?
推荐答案
如何最好地定位特定对象,然后深入到其子元素
how best to target a specific and then drill down to its child element
正确的XPath表达式是:
The correct XPath expression to do this is:
/resources/item[@id="index.php"]/description/text()
以简单的英语:从文档节点开始,到文档元素resources
,再到其子元素item
,但仅当id
属性的值为"index.php"时,再到其元素子description
并检索其文本值.
In plain English: Start from the document node, to the document element resources
, on to its child item
, but only if the value of the id
attribute is "index.php", on to its child description
and retrieve its textual value.
我使用xmllint来验证XML文档,但从未使用过路径表达式.在bash shell(至少在Mac OS中)中,有一个甚至更简单的工具来评估XPath表达式,称为"xpath":
I use xmllint to validate XML documents, but never for path expressions. In a bash shell (at least with Mac OS) there is an even simpler tool for evaluating XPath expressions, called "xpath":
$ xpath en.xml '/resources/item[@id="index.php"]/description/text()'
然后,获得以下结果:
Found 1 nodes:
-- NODE --
DESCRIPTION
如果您仍然喜欢xmllint,请按以下方式使用它:
If you still prefer xmllint, use it in the following way:
$ xmllint --xpath '/resources/item[@id="index.php"]/description/text()' en.xml > result.txt
默认情况下,--xpath
表示--noout
,这可防止xmllint输出任何内容.将输出重定向到文件.
By default, --xpath
implies --noout
, which prevents xmllint from outputting anything. Redirect the output to a file.
$ cat result.txt
DESCRIPTION
这篇关于带有XPATH的Linux Bash XMLLINT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!