Python: изменение файла XML
Я застрял, я написал код, который ищет определенный индекс в файле XML. Но когда я обнаружу, что Index не создаст мне новый XML-файл с этим индексом и постоянными параметрами. возвращает ошибку:
...rba_u_xml.py", line 29, in <module>
ObjectDictionary.remove(Variable)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 337, in remove
self._children.remove(element)
ValueError: list.remove(x): x not in list
это мой код:
import xml.etree.ElementTree 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):
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):
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):
ObjectDictionary.remove(Array)
tree.write('output.xml') #That would be amended to create a new xml file
Спасибо за вашу помощь! Я надеюсь, что вы понимаете (в другом случае спросите), потому что я часто использую Google переводчик:)
1 ответ
Я решил это!:D Insted из модуля xml.etree.ElementTree Я использую модуль xml и insted из ObjectDictionary.remove(Variable) Я использую Variable.clear()
Я использую модуль lxml
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
В новом xml файле теперь остались только теги переменных, записей и массивов.
<Group name="OptionalObjects">
<Array/><Array/><Variable/><Variable/><Variable/><Record/><Record/><Record/><Record/><Record/><Record/><Record/><Record/></Group>
У кого-нибудь есть идеи, как решить эту (надеюсь) последнюю проблему?