2013-04-20 44 views
4

我有一個XML文件,我想在其中編輯或重命名元素並保存該文件。什麼是最好的方式來做到這一點。 XML文件在下面給出重命名XML元素的Python

<breakfast_menu> 
<food> 
    <name>Belgian Waffles</name> 
    <price>$5.95</price> 
    <description>two of our famous Belgian Waffles with plenty of real maple syrup</description> 
    <calories>650</calories> 
</food> 
<food> 
    <name>Strawberry Belgian Waffles</name> 
    <price>$7.95</price> 
    <description>light Belgian waffles covered with strawberries and whipped cream</description> 
    <calories>900</calories> 
</food> 
<food> 
    <name>Berry-Berry Belgian Waffles</name> 
    <price>$8.95</price> 
    <description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description> 
    <calories>900</calories> 
</food> 
<food> 
    <name>French Toast</name> 
    <price>$4.50</price> 
    <description>thick slices made from our homemade sourdough bread</description> 
    <calories>600</calories> 
</food> 
<food> 
    <name>Homestyle Breakfast</name> 
    <price>$6.95</price> 
    <description>two eggs, bacon or sausage, toast, and our ever-popular hash browns</description> 
    <calories>950</calories> 
</food> 
</breakfast_menu> 

如何將「描述」更改爲「詳細信息」?

回答

-2

那麼你有兩個選擇。如果xml很小,則可以使用純字符串替換。如果xml非常大,那麼我會建議應用xsl轉換。

+0

爲什麼downvoted? – Raj 2013-04-20 14:23:31

+0

這只是較長文件的一部分。如何使用python進行xsl轉換 – user1138880 2013-04-20 14:25:09

6

我建議你使用ElementTree來解析你的XML文檔。

這是處理python中的XML文檔的簡單和最好的庫。

下面是一個例子代碼:

import xml.etree.ElementTree as xmlParser 
xmlDoc = xmlParser.parse('path to your xml doc') 
rootElement = xmlDoc.getroot() 

for element in rootElement.iter('description'): 
    element.tag = 'details' 

# Saving the xml 
xmlDoc.write('path to your new xml doc') 
+0

如何修復格式錯誤的XML,其中開始標記和關閉不匹配。就像在下面的XML中一樣 – user1138880 2013-04-20 15:42:55

0

如果您的XML將永遠留這個簡單,你可以使用正則表達式:

import re 
xml = """ 
<breakfast_menu> 
... 
</breakfast_menu> 
""" 
regex = re.compile('<description>(.*)</description>') 
xml = regex.sub(r'<details>\1</details>',xml) 
+0

如何修復開頭標籤和關閉不匹配的格式錯誤的XML。 – user1138880 2013-04-20 15:51:25

+0

您可以將正則表達式分解爲兩部分:打開= re.compile('')''closing = re.compile('')'。即使沒有結束標記,這將替換開始標記,但格式不正確的XML不會自動修復。 通常,使用正則表達式處理非常規標記並不是一個好主意。但是,如果您完全確定,正則表達式非常有效,您的輸入將始終遵循特定規則。 – 2013-04-20 23:01:54