2014-01-14 113 views
0

具体的数据我有这样提取XML文件

<pr_id>01</pr_id> 
    <uniprot>O11482</uniprot> 
    <uniprot>O96642</uniprot> 
    <uniprot>Q67845</uniprot> 
    <column> 
     <column_id>1</column_id> 
     column_start>300</column_start> 
     <column_end>334</column_end> 
     <old_new>old</old_new> 
     <comment></comment> 
    </column> 
    <column> 
     <column_id>2</column_id> 
     <column_start>335</column_start> 
     <column_end>337</column_end> 
     <old_new>new</old_new> 
     <comment></comment> 
     <pr_id>02</pr_id> 
     <uniprot>P4455</uniprot> 
     <uniprot>89WER8</uniprot> 
     <uniprot>Q12845</uniprot> 
      <column> 
     <column_id>1</column_id> 
     <column_start>12</column_start> 
     <column_end>34</column_end> 
     <old_new>old</old_new> 
     <comment></comment> 
     </column> 
     <column> 
     <column_id>2</column_id> 
     <column_start>35</column_start> 
     <column_end>37</column_end> 
     <old_new>old</old_new> 
     <comment></comment> 

我想获得如下输出XML文件。

pr_id uniprot old_start old_end 
01  O11482 300   334 
02  P4455 12   34 
02  P4455 35   37 

实现此目的的简单方法是什么?这是我第一次处理xml文件。您的宝贵意见将不胜感激!

+2

确保XML的简洁(wellformed)然后使用任何XML解析器。 – thefourtheye

+2

可能的重复:[如何在python中解析XML?](http://stackoverflow.com/questions/1912434/how-do-i-parse-xml-in-python) – valverij

+0

为什么你不想输出列没有。 2为'pr_id = 01'? –

回答

2

在了GNU AWK版本4,您可以使用split()功能:

gawk -f a.awk file.xml 

其中a.awk是:

BEGIN {RS="^$"} 
{ 
    n=split($0,a,/<\/?(uniprot|pr_id|column_start|column_end|old_new)>/,s) 
    for (i=1; i<=n-1;i+=2) { 
     if (s[i]=="<pr_id>") {pp=a[i+1]; up=0} 
     if (s[i]=="<uniprot>" && up==0) {uu=a[i+1];up=1} 
     if (s[i]=="<column_start>") ss=a[i+1] 
     if (s[i]=="<column_end>") ee=a[i+1] 
     if (s[i]=="<old_new>" && a[i+1]=="old") { 
      p[++k]=pp 
      u[k]=uu 
      s[k]=ss 
      e[k]=ee 
     } 
    } 
} 
END { 
    fmt="%5s%10s%10s%10s\n" 
    printf fmt, "pr_id", "uniprot", "old_start", "old_end" 
    for (i=1; i<=k; i++) 
     printf fmt,p[i],u[i],s[i],e[i] 
} 

输出:

pr_id uniprot old_start old_end 
    01 O11482  300  334 
    02  P4455  12  34 
    02  P4455  35  37 
+0

感谢您的回答。我没有得到我想要的输出。我得到了这样的输出pr_id uniprot old_start old_end 01 O11482我使用ubuntu12.04和刚安装的gawk使用命令sudo dpkg -i gawk_4.0.1 + dfsg-2_amd64.deb。请帮助我 – user3194459

+0

@ user3194459我也在使用Ubuntu 12.04。但我使用Gnu Awk版本4.1(不是版本4.0.1),也许你可以试试版本4.1? –

+0

非常感谢! – user3194459

1

取决于XML的大小,但为什么不使用python的minidom获得大小为30 megs或SAX的XML(如果您高于该值)。

即使Excel可能会诀窍,如果你只需要它一次。

但是,所有这些都依赖于格式良好的XML(将其拖入浏览器或使用某种XML工具进行验证)。你发布的XML似乎有点偏离。