xmlxpathxmlstarlet

XPath query with xmlstarlet


I have XML similar to this one:

<orders>
        <orderCompleteRequestType>
                <Head>
                        <Aufnr>11111</Aufnr>
                </Head>
                <Register>
                        <Id>180</Id>
                        <value1>11</value1>
                        <value2>22</value2>
                </Register>
                <Register>
                        <Id>181</Id>
                        <value1>3</value1>
                        <value2>43</value2>
                </Register>
                <Register>
                        <Id>160</Id>
                        <value1>5</value1>
                        <value2>25</value2>
                </Register>
        </orderCompleteRequestType>
        <orderCompleteRequestType>
                <Head>
                        <Aufnr>22222</Aufnr>
                </Head>
                <Register>
                        <Id>280</Id>
                        <value1>1</value1>
                        <value2>12</value2>
                </Register>
                <Register>
                        <Id>160</Id>
                        <value1>12</value1>
                        <value2>7</value2>
                </Register>
                <Register>
                        <Id>281</Id>
                        <value1>94</value1>
                        <value2>22</value2>
                </Register>
        </orderCompleteRequestType>
</orders>

I want to select in CSV format some values from each "orderCompleteRequestType" structure:

When using following command line:

xmlstarlet sel -T -t -m "/orders/orderCompleteRequestType" -v "Head/Aufnr" -o ";" -v "Register/Id" -o ";" -v "Register/value1" -o ";" -v "Register/value2" -n -n test.xml

I get:

11111;180
181
160;11
3
5;22
43
25

22222;280
160
281;1
12
94;12
7
22

so, first goes all values of Register/Id nodes, next all Register/value1's and finally all Register/value2's, but rather of this I expect something like:

11111;180;11;22
11111;181;3;43
11111;160;5;25

22222;280;1;12
22222;160;12;7
22222;281;94;22

Can anyone help me, because my brain rejecting to do work...


Solution

  • Instead of matching orderCompleteRequestType, consider matching Register instead...

    xmlstarlet sel -T -t -m "/orders/orderCompleteRequestType/Register" -v "concat(../Head/Aufnr,';',Id,';',value1,';',value2)" -n test.xml
    

    output...

    11111;180;11;22
    11111;181;3;43
    11111;160;5;25
    22222;280;1;12
    22222;160;12;7
    22222;281;94;22
    

    There isn't an extra newline between each orderCompleteRequestType, but maybe that's not a big deal? If it is, it might be easier to just write an XSLT and call that with xmlstarlet.