[英]Python - How to append the same XML element multiple times with lxml.objectify
我有以下XML,我試圖用lxml.objectify 包重新創建
<file>
<customers>
<customer>
<phone>
<type>home</type>
<number>555-555-5555</number>
</phone>
<phone>
<type>cell</type>
<number>999-999-9999</number>
</phone>
<phone>
<type>home</type>
<number>111-111-1111</number>
</phone>
</customer>
</customers>
</file>
我無法弄清楚如何多次創建手機元素。 基本上,我有以下非工作代碼:
# create phone element 1
root.customers.customer.phone = ""
root.customers.customer.phone.type = data_dict['PRIMARY PHONE1']
root.customers.customer.phone.number = data_dict['PRIMARY PHONE TYPE 1']
# create phone element 2
root.customers.customer.phone = ""
root.customers.customer.phone.type = data_dict['PRIMARY PHONE2']
root.customers.customer.phone.number = data_dict['PRIMARY PHONE TYPE 2']
# create phone element 3
root.customers.customer.phone = ""
root.customers.customer.phone.type = data_dict['PRIMARY PHONE3']
root.customers.customer.phone.number = data_dict['PRIMARY PHONE TYPE 3']
當然,這只會在生成的XML中輸出一部分電話信息。 有沒有人有任何想法?
您應該創建objectify.Element
對象,並將它們添加為root.customers
子root.customers
。
例如,插入兩個電話號碼可以這樣做:
phone = objectify.Element('phone')
phone.type = data_dict['PRIMARY PHONE1']
phone.number = data_dict['PRIMARY PHONE TYPE 1']
root.customers.customer.append(phone)
phone = objectify.Element('phone')
phone.type = data_dict['PRIMARY PHONE2']
phone.number = data_dict['PRIMARY PHONE TYPE 2']
root.customers.customer.append(phone)
如果在將xml轉換回字符串時獲得這些元素的不必要屬性,請使用objectify.deannotate(root, xsi_nil=True, cleanup_namespaces=True)
。 見LXML的客觀化文檔的精確參數objectify.deannotate
。
(如果您使用的是舊版本的lxml,其中不包含cleanup_namespaces
關鍵字參數,請執行以下操作:
from lxml import etree
# ...
objectify.deannotate(root, xsi_nil=True)
etree.cleanup_namespaces(root)
)
下面是一些使用客觀化E-Factory構造XML的示例代碼:
from lxml import etree
from lxml import objectify
E = objectify.E
fileElem = E.file(
E.customers(
E.customer(
E.phone(
E.type('home'),
E.number('555-555-5555')
),
E.phone(
E.type('cell'),
E.number('999-999-9999')
),
E.phone(
E.type('home'),
E.number('111-111-1111')
)
)
)
)
print(etree.tostring(fileElem, pretty_print=True))
我在這里硬編碼,但你可以轉換為數據循環。 這是否適用於您的目的?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.