2017-02-17 146 views
0

我有了這個小片XML的:獲取父標籤的屬性在XML

<tile x="764" y="491" z="7"> 
    <item id="1988"/> 
    <inside> 
     <item id="3972"/> 
    </inside> 
</tile> 
<tile x="764" y="492" z="7"> 
    <item id="2343"/> 
</tile> 
<tile x="764" y="491" z="7"> 
    <item id="2000"/> 
    <inside> 
     <item id="3972" special_description="whatever"/> 
    </inside> 
</tile> 
<tile x="765" y="491" z="7"> 
    <item id="2114"/> 
</tile> 
<tile x="764" y="491" z="7"> 
    <item id="1988"/> 
</tile> 

我想獲得基於在項目標記中的特定屬性的搜索並列屬性的細節。例如,如果我找3972,我會得到的是這樣的結果:

x="764" y="491" z="7" : id="3972" 
x="764" y="491" z="7" : id="3972" special_description="whatever" 

顯然如何,只要我只有我的細節到底是措辭的結果是不是真的很重要如果[[item]]中包含[[id =「3972」]],並顯示該[[item]]的屬性,並且省略[[tile]]標籤的屬性其他瓷磚。

我用XMLStarlet試過我的運氣,但到目前爲止我沒有運氣,任何線索?

+1

可以向我們展示XMLStarlet嘗試嗎? –

+0

我當時大部分時間都在使用現在無法分辨的基本功能,離開我的機器工作。 –

回答

0

只是爲了好玩,你可以給一個嘗試這一個:

$ term="2114";awk -v term=$term '{a[NR]=$0; if ($0 ~ term) \ 
{i=NR;while (a[i] !~ "<tile x=.+ y=.+ z=.+") i--; \ 
print gensub(/(<tile) (.+)(>)/,"\\2","g",a[i]),":", \ 
gensub(/([ ]*)(<item)(.+)(\/>)/,"\\3","g",$0)}} ' file5 

Offcourse使用合適解析器爲該類型的數據應該是您的第一選擇。同時,看起來上面工作正常(用所有建議的數據進行測試)。

0

@this蓋伊:嘗試:

awk '/<tile/{A=1} /<\/tile>/{A="";if(VAL ~ /3972/){print VAL;};VAL=""} /<\/inside/{B=""} /<inside/{B=1} A{gsub(/tile |>|<|\/|inside/,"");if(B){sub(/item id/,": id")};if(!B){gsub(/item id=.*|^[[:space:]]+/,"")};VAL=VAL?VAL OFS $0:$0}' Input_file 

NON-一個溶液班輪形式如下太。

awk '/<tile/{ 
       A=1 
      } 
    /<\/tile>/{ 
       A=""; 
       if(VAL ~ /3972/){ 
             print VAL; 
           }; 
       VAL="" 
       } 
    /<\/inside/{ 
         B="" 
       } 
    /<inside/{ 
       B=1 
       } 
    A{ 
     gsub(/tile |>|<|\/|inside/,""); 
     if(B){ 
       sub(/item id/,": id") 
      }; 
     if(!B){ 
       gsub(/item id=.*|^[[:space:]]+/,"") 
       }; 
     VAL=VAL?VAL OFS $0:$0 
     } 
    ' Input_file 

輸出如下。

x="764" y="491" z="7"    : id="3972" 
x="764" y="491" z="7"    : id="3972" special_description="whatever"