我有以下 XML 檔案:
<customer>
<id>807997287</id>
<dateCreated>2022-11-13T00:00:00Z</dateCreated>
<status>Created</status>
<client>
<id>807997223</id>
<firstname>Jeff</firstname>
<lastname>Smith</lastname>
<address>
<id>4388574</id>
<home>
<addressLine1>Address Line 1</addressLine1>
<addressLine2>Address Line 2</addressLine2>
<addressLine3>Address Line 3</addressLine3>
<addressLine4>Address Line 4</addressLine4>
<postCode>XXX ZZZ</postCode>
</home>
<telephoneNumbers>
<telephone>
<id>807997230</id>
<areaCode>01123</areaCode>
<phoneNumber>123123</phoneNumber>
<usage>Work</usage>
</telephone>
<telephone>
<id>807997232</id>
<areaCode>01564</areaCode>
<phoneNumber>123123</phoneNumber>
<usage>Home</usage>
</telephone>
</telephoneNumbers>
</address>
</client>
</customer>
而且我需要能夠洗掉所有 ID 節點。
我嘗試了以下代碼,但它沒有 A) 找到所有 ID B) 沒有洗掉它們
import xml.etree.ElementTree as ET
tree = ET.ElementTree()
tree.parse('test.xml')
root = tree.getroot()
ids = root.findall(".//id")
for item in ids:
ids.remove(item)
print(ET.tostring(item))
t = ET.ElementTree(root)
t.write("output.xml")
命令列輸出為:
b'<id>807997287</id>\n '
b'<id>4388574</id>\n '
b'<id>807997232</id>\n '
并且 output.xml 保持不變。
任何人都可以幫我指出正確的方向嗎?
uj5u.com熱心網友回復:
您可能正在尋找類似的東西
##for elem in root.findall('.//*[id]'):
EDIT
for elem in root.findall('.//id/..'):
id = elem.find('.//id')
elem.remove(id)
print(ET.tostring(root).decode())
輸出應該是您的預期輸出。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/527433.html
標籤:Pythonxml元素树
