2016-05-09 110 views
0

我想使用xml.etree.ElementTree基於xml模板(template.xml)生成一個新的xml文件(new.xml)。我們的想法是隻將<name>標記的值從'all'更改爲'New',其餘的new.xml文件與template.xml完全一致。我可以改變<name>的值,但new.xml看起來不完全一樣TEMPLATE.XMLPython:根據xml模板編寫一個新的xml文件

這裏是TEMPLATE.XML:

<?xml version="1.0"?> 
<example> 
    <version>15.0</version> 
    <lastchange/> 
    <theme>black</theme> 
    <group> 
    <name>all</name> 
    <description><![CDATA[All Users]]></description> 
    <scope>system</scope> 
    <gid>1998</gid> 
    </group> 
</example> 

這裏是new.xml:

<example> 
    <version>15.0</version> 
    <lastchange /> 
    <theme>black</theme> 
    <group> 
    <name>New</name> 
    <description>All Users</description> 
    <scope>system</scope> 
    <gid>1998</gid> 
    </group> 
</example> 

正如你可以看到,在第一行缺少new.xml和<description>標籤的價值沒有![CDATA] []結構。這是我寫的腳本和我正在使用的腳本:

import xml.etree.ElementTree as ET 

def load_xml(name): 
    ''' Takes an xml file as input. Outputs ElementTree and element''' 
    tree = ET.parse(name) 
    root = tree.getroot() 
    return tree, root 

if __name__ == "__main__": 
    # Change and write the new xml 
    tree, root = load_xml('template.xml') 
    group = root.find('group') 
    group.find('name').text = 'New' 
    tree.write('new.xml') 

任何幫助?謝謝

+0

'ElementTree'核心蟒蛇似乎不支持CData部分:[1](http://stackoverflow.com/questions/174890/how-to-output-cdata-using-elementtree),[2](http://stackoverflow.com/questions/9027081/lxml- etree-fromsting - 和 - 的toString-ARE-未返回最相同數據)。如何切換到'lxml'? – har07

+1

擺脫XML聲明和CDATA節是否是一個問題?最後,這是相同的信息集。 –

+0

你是說xml聲明和CDATA節的存在與否不會改變結果嗎?即template.xml和new.xml被解釋爲相同的文件? – diegus

回答

0

lxml提供兼容的API,所以你只需要指定strip_cdata=False參數,並使用完全相同的代碼在其他地方:

form lxml import etree as ET 

def load_xml(name): 
    ''' Takes an xml file as input. Outputs ElementTree and element''' 
    # specify parser setting 
    parser = ET.XMLParser(strip_cdata=False) 
    # pass parser to do the actual parsing 
    tree = ET.parse(name, parser) 

    root = tree.getroot() 
    return tree, root 

if __name__ == "__main__": 
    # Change and write the new xml 
    tree, root = load_xml('template.xml') 
    group = root.find('group') 
    group.find('name').text = 'New' 
    tree.write('new.xml') 
+0

這似乎運作良好。謝謝! – diegus