Python: Modifying an XML File

﹥>﹥吖頭↗ 提交于 2019-12-02 10:11:45

I solved it! :D Insted of xml.etree.ElementTree modul I use xml module and insted of ObjectDictionary.remove(Variable) I use Variable.clear()

I use lxml module

from lxml import etree as ET
tree = ET.parse('master.xml')
root = tree.getroot()

-

s = input('Insert a number of index and add quotes(") befor and after: ')
i = int(s, 16)

for MagicNumber in root.findall('MagicNumber'):   #constant parameters
    print MagicNumber.tag,':', MagicNumber.text
    print('\n')
for FileInfo in root.find('FileInfo'):
    print FileInfo.tag,':', FileInfo.text
print''
for DeviceInfo in root.find('DeviceInfo'):
    print DeviceInfo.tag,':', DeviceInfo.text
print''
for DummyUsage in root.find('DummyUsage'):
    print DummyUsage.tag,':', DummyUsage.text
print''
for ObjectDictionary in root.find('ObjectDictionary'):
    name=ObjectDictionary.get('name')
    print ObjectDictionary.tag,':', ObjectDictionary.text, name
    print''                                                       #constant parameters

    for Variable in ObjectDictionary.iter('Variable'):          #searching for Variables in index
        if Variable.find('./Index').text == str(i):
            print 'Variable name: ', Variable.attrib['name']
        elif Variable.find('./Index').text != str(i):
            Variable.clear()                         #insted of ObjectDictionary.remove(Variable)

    for Record in ObjectDictionary.iter('Record'):             #searching for Records in index
        if Record.find('./Index').text == str(i):
            print 'Record name: ', Record.attrib['name']
        elif Record.find('./Index').text != str(i):
            Record.clear()                             #insted of ObjectDictionary.remove(Record)

    for Array in ObjectDictionary.iter('Array'):               #searching for Arrays in index
        if Array.find('./Index').text == str(i):
            print 'Array name: ', Array.attrib['name']
        elif Array.find('./Index').text != str(i):
            Array.clear()                               #insted of ObjectDictionary.remove(Array)


tree.write('output.xml')            #create a new xml file

In new xml file is now left just tags of variables,records and arrays.

<Group name="OptionalObjects"> <Array/><Array/><Variable/><Variable/><Variable/><Record/><Record/><Record/><Record/><Record/><Record/><Record/><Record/></Group>

Have anybody any idea how to solved out this (I hope) last problem?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!