xmlstarlet select value
Asked Answered
N

1

29

This is the xml-data:

<DATA VERSION="1.0">
  <TABLES>
    <ITEM>
      <identifyer V="1234"></identifyer>
      <property1 V="abcde"></property1>
      <Property2 V="qwerty"></property2>
    </ITEM>
    <ITEM>
      <identifyer V="5678"></identifyer>
      <Property1 V="zyxwv"></property1>
      <Property2 V="dvorak"></property2>
    </ITEM>
  </TABLES>
</DATA>

I am trying to find property2 of the item where identifyer has value 1234. I can select the data:

$ xmlstarlet sel -t -c "/DATA/TABLES/ITEM/identifyer [@V=1234]" test.xml 
<identifyer V="1234"/>

Two types of output would be desirable:

$ xmlstarlet <some magic>
<identifyer V="1234"></identifyer>
<property1 V="abcde"></property1>
<Property2 V="qwerty"></property2>

And:

$ xmlstarlet <some magic>
qwerty
Neilla answered 28/9, 2012 at 12:36 Comment(0)
S
53

The key is to start from the ITEM node, not the identifyer:

$ xmlstarlet sel -t -c "/DATA/TABLES/ITEM[identifyer/@V=1234]" test.xml
<ITEM>
  <identifyer V="1234"/>
  <property1 V="abcde"/>
  <Property2 V="qwerty"/>
</ITEM>

Then you can pick out the bits you want:

$ xmlstarlet sel -t -c "/DATA/TABLES/ITEM[identifyer/@V=1234]/*" test.xml
<identifyer V="1234"/><property1 V="abcde"/><Property2 V="qwerty"/>

$ xmlstarlet sel -t -v "/DATA/TABLES/ITEM[identifyer/@V=1234]/Property2/@V" test.xml
qwerty
Spirit answered 28/9, 2012 at 17:53 Comment(1)
Great, that works :) Good to see the syntax in an example, I can get forward with this. Thanks!Neilla

© 2022 - 2024 — McMap. All rights reserved.