2016-07-07 196 views
0

我想使用bash過濾example-below xml。從xml獲取屬性名稱

問題: 如果子節點att =「t」的屬性存在,則應該打印屬性名稱。

輸入:

<?xml version="1.0" encoding="UTF-8"?> 
<general> 
    <node1> 
     <subnode att1="a" att2="t" name="test"> </subnode> 
     <subnode att1="a" name="test2"> </subnode> 
     <subnode att1="a" name="test3"> </subnode> 
     <subnode att1="a" att2="t" name="test4"> </subnode> 
    </node1> 
</general> 

輸出:

test 
test4 

我試圖grep和xmllint,但沒有成功。

我的 「臨時」 的解決方案是:

xmllint --xpath 'string(//general/node1/subnode[@att2="t"]/@name)' file.xml 

但該命令只打印第一次出現 - 測試。

回答

0

不是你問的相當的東西,但用perl(和XML解析器)應該是你的系統上容易獲得這兩個:(比如他們都應該通過包管理器可以在大多數發行版 - XML::Twig也可以通過cpan下載如果你喜歡)

#!/usr/bin/env perl 
use strict; 
use warnings; 
use XML::Twig; 

my $twig = XML::Twig->parse(\*DATA); 

print $_->att('name'),"\n" for $twig->get_xpath('//subnode[@att2="t"]'); 

__DATA__ 
<?xml version="1.0" encoding="UTF-8"?> 
<general> 
    <node1> 
     <subnode att1="a" att2="t" name="test"> </subnode> 
     <subnode att1="a" name="test2"> </subnode> 
     <subnode att1="a" name="test3"> </subnode> 
     <subnode att1="a" att2="t" name="test4"> </subnode> 
    </node1> 
</general> 

作爲一個襯墊,這成爲:

perl -0777 -MXML::Twig -e 'print $_->att("name"),"\n" for XML::Twig->parse(<>)->get_xpath(q{//subnode[@att2="t"]})' 

這一個襯墊可以在同樣的方式AWK/SED/grep的如使用作爲管道xml的地方,或者用命令行指定的文件。

0

請檢查,如果這個工程

awk '{if(/att[0-9]="t"/){line=$0;replacedLine=substr(line,index(line,"name="));gsub(/name="/,"",replacedLine);endIndex=index(replacedLine,"\"");print substr(replacedLine,0,endIndex);}}' xmlfile 
+0

不工作,有時打印其他屬性。 – profiler

+0

我需要非工作案例的XML內容,以便我可以修復。請更新您的問題更少的情況下。另外,我的代碼假設你想匹配包含att [any_number] =「t」的行。不是嗎?你只需要匹配att2 =「t」? – 2016-07-07 12:06:59

0

使用xmlstarlet:如果你必須使用xmllint

xmlstarlet sel -t -v '//general/node1/subnode[@att2="t"]/@name' -nl 

,那麼這樣做:

xmllint --xpath '//general/node1/subnode[@att2="t"]/@name' sample.xml \ 
    | sed 's/ name="//g; s/"/\n/g;' 
+0

xmlstarlet不是標準命令......最好的解決方案是使用xmllint。 – profiler

+1

你的意思是它不在你的**系統上。 –

+0

是的,確實如此。我想使用那個命令哪一個在linux上。 – profiler