2016-10-19 99 views
1

我有一個XML與蟒蛇排序XML的標記

<root> 
<node1> 
    <B>text</B> 
    <A>another_text</A> 
    <C>one_more_text</C> 
</node1> 
<node2> 
    <C>one_more_text</C> 
    <B>text</B> 
    <A>another_text</A> 
</node2> 
</root> 

我想要得到的輸出,如:

from xml.etree import ElementTree as et 

tr = et.parse(path_in) 
root = tr.getroot() 
for children in root.getchildren(): 
    for child in children.getchildren(): 
     # sort it 

tr.write(path_out)   

我不能使用:

<root> 
<node1> 
    <A>another_text</A> 
    <B>text</B> 
    <C>one_more_text</C> 
</node1> 
<node2> 
    <A>another_text</A> 
    <B>text</B> 
    <C>one_more_text</C> 
</node2> 
</root> 

我喜歡的一些代碼試圖標準功能sortsorted,因爲它排序錯誤(而不是標籤)。 在此先感謝。

回答

1

您需要:

  • 讓孩子們元素fo [R
  • 每個頂級「節點」
  • tag attribute(節點名稱)排序它們重置每個頂級節點的子節點

樣品工作代碼:

from operator import attrgetter 
from xml.etree import ElementTree as et 

data = """ <root> 
<node1> 
    <B>text</B> 
    <A>another_text</A> 
    <C>one_more_text</C> 
</node1> 
<node2> 
    <C>one_more_text</C> 
    <B>text</B> 
    <A>another_text</A> 
</node2> 
</root>""" 


root = et.fromstring(data) 
for node in root.findall("*"): # searching top-level nodes only: node1, node2 ... 
    node[:] = sorted(node, key=attrgetter("tag")) 

print(et.tostring(root)) 

打印:

<root> 
<node1> 
    <A>another_text</A> 
    <B>text</B> 
    <C>one_more_text</C> 
</node1> 
<node2> 
    <A>another_text</A> 
    <B>text</B> 
    <C>one_more_text</C> 
    </node2> 
</root> 

請注意,我們在這裏沒有使用getchildren() method(這是一個從Python 2.7開始,不推薦使用) - 使用每個Element實例都是可迭代子節點的事實。

2

從一個類似的問題:

from lxml import etree 

data = """<X> 
    <X03>3</X03> 
    <X02>2</X02> 
    <A> 
     <A02>Y</A02> 
     <A01>X</A01> 
     <A03>Z</A03> 
    </A> 
    <X01>1</X01> 
    <B> 
     <B01>Z</B01> 
     <B02>X</B02> 
     <B03>C</B03> 
    </B> 
</X>""" 

doc = etree.XML(data,etree.XMLParser(remove_blank_text=True)) 

for parent in doc.xpath('//*[./*]'): # Search for parent elements 
    parent[:] = sorted(parent,key=lambda x: x.tag) 

print etree.tostring(doc,pretty_print=True) 

結果:

<X> 
    <A> 
    <A01>X</A01> 
    <A02>Y</A02> 
    <A03>Z</A03> 
    </A> 
    <B> 
    <B01>Z</B01> 
    <B02>X</B02> 
    <B03>C</B03> 
    </B> 
    <X01>1</X01> 
    <X02>2</X02> 
    <X03>3</X03> 
</X> 

你可以在這裏找到更多的信息:http://effbot.org/zone/element-sort.htm