2012-09-28 55 views
12

這是XML的數據:xmlstarlet選擇值

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

我試圖尋找到identifyer具有價值1234項目的property2。我可以選擇的數據:

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

兩種類型的輸出的希望:

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

和:

$ xmlstarlet <some magic> 
qwerty 

回答

19

的關鍵是從項目節點開始,而不是identifyer :

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

然後你可以挑選你想要的位:

$ 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 
+0

偉大的,那工作:)很高興看到一個例子中的語法,我可以得到與此。謝謝! – joepd