Search code examples
xmlxml-parsingxmlstarlet

How to query xml (invalid expression)?


Part of the xml file:

<caldata chopper="on" gain_1="0" gain_2="0" gain_3="0" impedance="(0,0)">
  <c0 unit="V">0.00000000e+00</c0>
  <c1 unit="Hz">4.00000000e-01</c1>
  <c2 unit="V/(nT*Hz)">1.93430000e-02</c2>
  <c3 unit="deg">8.92260000e+01</c3>
</caldata>
<caldata chopper="on" gain_1="0" gain_2="0" gain_3="0" impedance="(0,0)">
  <c0 unit="V">0.00000000e+00</c0>
  <c1 unit="Hz">5.55800000e-01</c1>
  <c2 unit="V/(nT*Hz)">1.93390000e-02</c2>
  <c3 unit="deg">8.89710000e+01</c3>
</caldata>
<caldata chopper="on" gain_1="0" gain_2="0" gain_3="0" impedance="(0,0)">
  <c0 unit="V">0.00000000e+00</c0>
  <c1 unit="Hz">7.72300000e-01</c1>
  <c2 unit="V/(nT*Hz)">1.93320000e-02</c2>
  <c3 unit="deg">8.86030000e+01</c3>
</caldata>

I want to extract numerical values on c2 line. This is my try:

 xmlstarlet sel -t -v '//caldata chopper="on"[<c2 unit="V/(nT*Hz)"> ]' 263.xml 
Invalid expression: //caldata chopper="on"[<c2 unit="V/(nT*Hz)"> ]
compilation error: element with-param
XSLT-with-param: Failed to compile select expression '//caldata chopper="on"[<c2 unit="V/(nT*Hz)"> ]'
 xmlstarlet sel -t -v '//caldata chopper="on"[<c2 unit="V/(nT*Hz)"> ]' 263.xml 
Invalid expression: //caldata chopper="on"[<c2 unit="V/(nT*Hz)"> ]
compilation error: element with-param
XSLT-with-param: Failed to compile select expression '//caldata chopper="on"[<c2 unit="V/(nT*Hz)"> ]'

What should I change? Is xmlstarlet the right tool for this?


Solution

  • xmlstarlet is perfectly suited for this task. Try:

    xmlstarlet sel -t -v '//caldata[@chopper="on"]/c2[@unit="V/(nT*Hz)"]' 263.xml
    

    Result:

    1.93430000e-02
    1.93390000e-02
    1.93320000e-02