0
votes

I have this xml schema , could you possible help me to extract the values of all item, using XMLStarlet, in shell script.

<transfer-matrix.xml>
    <transfers>
        <rows>
            <item>
                <item>Hungary</item>
                <item>Kharkov-KIPT-LCG2</item>
                <item>9882899680</item>
                <item>4</item>
                <item>1</item>
            </item>
            <item>
                <item>Spain</item>
                <item>Kharkov-KIPT-LCG2</item>
                <item>32945102817</item>
                <item>12</item>
                <item>2</item>
            </item>
            <item>
                <item>Finland</item>
                <item>Kharkov-KIPT-LCG2</item>
                <item>10737418240</item>
                <item>4</item>
                <item>0</item>
            </item>
            <item>...</item>
            <item>...</item>
            <item>...</item>
        </rows>
        <key>...</key>
    </transfers>
<params>...</params>
</transfer-matrix.xml>

I'm trying to extract item in such way

outcome=`xml sel -T -t -m /transfer-matrix.xml/transfers/rows/item -s D:N:- "@item" -v "concat(@item,'|',item,'|',item,'|',item,'|',item,'|',item)" -n /usr/share/dashboard/xml/transfers-country.xml`

My output is:

|Hungary|Hungary|Hungary|Hungary|Hungary |Spain|Spain|Spain|Spain|Spain |Finland|Finland|Finland|Finland|Finland

I need format like this

|Hungary|Kharkov-KIPT-LCG2|9882899680|4|1
|Spain|Kharkov-KIPT-LCG2|32945102817|12|2 
|Finland|Kharkov-KIPT-LCG2|10737418240|4|0

I would be grateful for the help

1

1 Answers

0
votes

You need to specify which element you want and add new line character in the end like this:

OUTPUT=$(xmlstarlet sel -T -t -m /transfer-matrix.xml/transfers/rows/item -s D:N:- "@item" -v "concat(@item,'|',item[1],'|',item[2],'|',item[3],'|',item[4],'|',item[5],'\n')" transfers-country.xml)

And then you can get the desired result via echo -e:

$ echo -e "$OUTPUT"
|Hungary|Kharkov-KIPT-LCG2|9882899680|4|1
|Spain|Kharkov-KIPT-LCG2|32945102817|12|2
|Finland|Kharkov-KIPT-LCG2|10737418240|4|0

Edit: As npostavs points out, it would be much better to use -n flag instead:

$ xmlstarlet sel -T -t -m /transfer-matrix.xml/transfers/rows/item -s D:N:- "@item" -n -v "concat(@item,'|',item[1],'|',item[2],'|',item[3],'|',item[4],'|',item[5])" transfers-country.xml

|Hungary|Kharkov-KIPT-LCG2|9882899680|4|1
|Spain|Kharkov-KIPT-LCG2|32945102817|12|2
|Finland|Kharkov-KIPT-LCG2|10737418240|4|0