#python #xml
#python #xml
Вопрос:
Формат XML выглядит следующим образом :
<?xml version='1.0' encoding='utf8'?>
<con:PropertySet xmlns:con="HTTP://example.com/SCHEMA"> <con:properties>
<con:property>
<con:description>test1</con:description>
<con:name>Kate</con:name>
<con:defaultValue>
<con:value>false</con:value>
</con:defaultValue
</con:property>
<con:property>
<con:description>test2</con:description>
<con:name>Nathan</con:name>
<con:defaultValue>
<con:value>false</con:value>
</con:defaultValue
</con:property>
</con:properties>
</con:PropertySet>
Я попробовал код как новичок:
with open(test.xml, encoding="utf8") as f:
tree = ET.parse(f)
print("tree : ", tree)
myroot = tree.getroot()
print("myroot",myroot)
result = len(myroot.getchildren())
print("length", result)
for elem in myroot.iter():
try:
value_find = myroot.find("./PropertySet/properties/property/defaultValue/[@value='false']")
print("property", value_find)
Оператор Last print не выдает никаких выходных данных. Нет выходных данных.
Здесь я пытаюсь добиться замены false на true тега на основе Name = Kate.
Не могли бы вы, пожалуйста, помочь мне.
Ответ №1:
ниже
import xml.etree.ElementTree as ET
xml = '''<?xml version="1.0" encoding="UTF-8"?>
<con:PropertySet xmlns:con="HTTP://example.com/SCHEMA">
<con:properties>
<con:property>
<con:description>test1</con:description>
<con:name>Kate</con:name>
<con:defaultValue>
<con:value>false</con:value>
</con:defaultValue>
</con:property>
<con:property>
<con:description>test2</con:description>
<con:name>Nathan</con:name>
<con:defaultValue>
<con:value>false</con:value>
</con:defaultValue>
</con:property>
</con:properties>
</con:PropertySet>'''
namespaces = {'con': 'HTTP://example.com/SCHEMA'}
ET.register_namespace('con', 'HTTP://example.com/SCHEMA')
root = ET.fromstring(xml)
kates = [e for e in root.findall('.//con:property', namespaces) if e.find('con:name', namespaces).text == 'Kate']
for kate in kates:
kate.find('.//con:value', namespaces).text = 'true'
ET.dump(root)
вывод
<con:PropertySet xmlns:con="HTTP://example.com/SCHEMA">
<con:properties>
<con:property>
<con:description>test1</con:description>
<con:name>Kate</con:name>
<con:defaultValue>
<con:value>true</con:value>
</con:defaultValue>
</con:property>
<con:property>
<con:description>test2</con:description>
<con:name>Nathan</con:name>
<con:defaultValue>
<con:value>false</con:value>
</con:defaultValue>
</con:property>
</con:properties>
</con:PropertySet>