Multiple matches of xml to single csv row (xmlstarlet)

Viewed 515

XML Sample:

<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>

I try to export entries to CSV file like this:

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

with xmlstarlet, guiding with:

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"

But my result is different from the expected:

$ 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

It is evident to use grep like workaround (that's exactly what I did), but I want to understand how to use it properly and what caused this unobvious behavior.

1 Answers

You're not using the option -m correctly.

The -m option is the xpath from where you extract values (with -v option).

So your query should be:

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

where hosts/host is the root of your search query.

Related