2017-02-17 91 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"