簡體   English   中英

Python - 如何使用lxml.objectify多次附加相同的XML元素

[英]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.customersroot.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM