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

Multiple matches of xml to single csv row (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

xmlstarletguiding 与:

There can be multiple --match, --copy-of, --value-of, etc options in a single template. The effect of applying command line templates can be illustrated with the following XSLT analogue

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 之类的解决方法(这正是我所做的),但我想了解如何正确使用它以及导致这种不明显行为的原因。

您没有正确使用 -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 是搜索查询的根。