Python如何使用lxml.objectify

2024-10-01 11:31:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的XML,我试图用lxml.objectifypackage

<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>

我不知道如何多次创建phone元素。基本上,我有以下非工作代码:

^{pr2}$

当然,它只在结果XML中输出电话信息的一部分。有人有什么想法吗?在


Tags: 代码元素numberhometypephonecellcustomer
2条回答

下面是一些使用objectify 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))

我已经在这里硬编码了,但是你可以转换成一个循环覆盖你的数据。这对你有用吗?在

您应该创建objectify.Element对象,并将它们添加为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)

{3>在转换这些不必要的属性时使用cd3}。 有关objectify.deannotate的确切参数,请参见lxml's objectify documentation。在

(如果您使用的是旧版本的lxml,它不包括cleanup_namespaces关键字参数,请改为执行以下操作:

^{pr2}$

相关问题 更多 >