Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
根据特定标记的内容从XML中提取数据_Xml_Bash - Fatal编程技术网

根据特定标记的内容从XML中提取数据

根据特定标记的内容从XML中提取数据,xml,bash,Xml,Bash,我有一个如下所示的xml文件: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns1:policies xmlns:ns1="http://www.companyname.nl/exchange/policyimport" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <policy> <serial

我有一个如下所示的xml文件:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns1:policies xmlns:ns1="http://www.companyname.nl/exchange/policyimport" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <policy>
        <serialnumber>159</serialnumber>
        <relationnumber>159</relationnumber>
        <policynumber>2013000001</policynumber>
        <soort>2002</soort>
        <policyStatus>1</policyStatus>
        <startdate>2001-03-16</startdate>
        <enddate>2016-03-16</enddate>
        <label1>0</label1>
        <label2>100</label2>
        <btw>true</btw>
    </policy>
    <policy>
        <serialnumber>159</serialnumber>
        <relationnumber>159</relationnumber>
        <policynumber>2013000002</policynumber>
        <soort>2003</soort>
        <policyStatus>1</policyStatus>
        <startdate>2001-03-16</startdate>
        <enddate>2016-03-16</enddate>
        <label1>0</label1>
        <label2>100</label2>
        <btw>false</btw>
    </policy>
</ns1:policies>

159
159
2013000001
2002
1.
2001-03-16
2016-03-16
0
100
真的
159
159
2013000002
2003
1.
2001-03-16
2016-03-16
0
100
假的
我想使用bash脚本从标记中提取数据,但这取决于另一个标记的内容。 例如: 如果
的内容为true,则在同一块中获取
的内容(在本例中为2013000001)

如果
的内容是2003,则在同一块中获取
的内容(在本例中为2013000002)

这在bash脚本中可能吗?我试图用xmlstarlet解决这个问题,但我是一个新手,无法完成。
蒂亚

xmllint
与其xpath内置项一起使用。检查它在当前xmllint二进制文件中是否可用。否则,您需要重新编译xmllint

xmllint--help | grep“\-\-xpath”

如果可用,您可以使用:

xmllint--xpath//policy/btw[text()='true']/../policynumber“xmllint xpath.file


该命令退出所有策略
//policy
检查btw的文本值
btw[text()='true']
,如果这是真的,则首先通过向上移动
的名称来收集btw的兄弟姐妹。

xmlstarlet命令将返回所有
值,用空格分隔,在
s内且
值等于“true”的:

xml sel -t -m "//policy/btw[. = 'true']/../policynumber" -v "." -o " " in.xml

如果有名称空间前缀,则上述操作似乎不起作用。此处不需要名称空间前缀。它已经用OP的XML进行了测试,并且按照要求工作。我的意思是,如果XML中的每个元素都有名称空间前缀,xpath也需要相同的前缀。当然,您提供的命令适用于原始文章中给定的xml。