2012-09-28 58 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