2012-09-28 29 views
12

Đây là xml-data:xmlstarlet chọn giá trị

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

Tôi cố gắng để tìm property2 của mặt hàng đó ở đâu identifyer có giá trị 1234. Tôi có thể chọn dữ liệu:

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

Hai loại đầu ra sẽ được mong muốn:

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

Và:

$ xmlstarlet <some magic> 
qwerty 

Trả lời

19

Điều quan trọng là phải bắt đầu từ nút ITEM, không phải là identifyer :

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

Sau đó, bạn có thể chọn các bit bạn muốn:

$ 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

Tuyệt vời, hoạt động :) Tốt để xem cú pháp trong ví dụ, tôi có thể tiếp tục với điều này. Cảm ơn! – joepd