xml与单个csv行的多个匹配(xmlstarlet)

时间:2018-11-14 10:25:51

标签: xml csv export-to-csv xmlstarlet

XML示例:

<hosts>
    <host>
        <name>Server A</name>
        <status>0</status>
        <groups>
            <group>
                <name>Discovered hosts</name>
            </group>
        </groups>
        <interfaces>
            <interface>
                <ip>10.1.2.3</ip>
            </interface>
        </interfaces>
    </host>
    <host>
        <name>Server B</name>
        <status>0</status>
        <groups>
            <group>
                <name>Discovered hosts</name>
            </group>
        </groups>
        <interfaces>
            <interface>
                <ip>10.1.2.4</ip>
            </interface>
        </interfaces>
    </host>
</hosts>

我尝试将条目导出到CSV文件,如下所示:

Discovered hosts,Server A,10.1.2.3,0
Discovered hosts,Server B,10.1.2.4,0

使用xmlstarlet,使用guiding使用:

  

一个选项中可以有多个--match,-copy-of,-value-of等选项   单个模板。应用命令行模板的效果可以是   下面的XSLT类似物进行了说明

     

xml sel -t -c“ xpath0” -m“ xpath1” -m“ xpath2” -v“ xpath3” \           -t -m“ xpath4” -c“ xpath5”

但是我的结果与预期的不同:

$ xmlstarlet sel -t \
-m "//host/groups/group/name" -v . -o "," \
-m "//host/name" -v . -o "," \
-m "//host/interfaces/interface/ip" -v . -o "," \
-m "//host/status" -v . -n sample.xml 
Discovered hosts,Server A,10.1.2.3,0
0
10.1.2.4,0
0
Server B,10.1.2.3,0
0
10.1.2.4,0
0
Discovered hosts,Server A,10.1.2.3,0
0
10.1.2.4,0
0
Server B,10.1.2.3,0
0
10.1.2.4,0
0

使用grep这样的解决方法很明显(这正是我所做的),但是我想了解如何正确使用它以及导致这种不明显行为的原因。

1 个答案:

答案 0 :(得分:1)

您没有正确使用选项-m

-m选项是从中提取值的xpath(使用-v选项)。

所以您的查询应该是:

xmlstarlet sel -t -m "hosts/host" \
                  -v "groups/group/name" -o "," \
                  -v "name" -o "," \
                  -v "interfaces/interface/ip" -o "," \
                  -v "status" \
                  -n file

其中hosts/host是搜索查询的根。