XPath query with xmlstarlet

荒凉一梦 提交于 2021-02-19 03:42:34

问题


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:

  • Head/Aufrn
  • Register/Id
  • Register/value1
  • Register/value2

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


回答1:


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.



来源:https://stackoverflow.com/questions/48664625/xpath-query-with-xmlstarlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!