我尝试使用lxml.objectify package重新创建以下XML
<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元素。基本上,我有以下不能工作的代码:
# 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中只输出电话信息的一部分。有谁有什么想法吗?
发布于 2012-09-08 04:15:47
您应该创建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)如果在将xml转换回字符串时在这些元素上获得了不必要的属性,请使用objectify.deannotate(root, xsi_nil=True, cleanup_namespaces=True)。objectify.deannotate的确切参数请参见lxml's objectify documentation。
(如果您使用的是不包含cleanup_namespaces关键字参数的旧版本的lxml,请执行以下操作:
from lxml import etree
# ...
objectify.deannotate(root, xsi_nil=True)
etree.cleanup_namespaces(root))
发布于 2012-09-08 04:21:42
下面是一些使用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))我在这里对其进行了硬编码,但您可以将其转换为数据上的循环。这对你的目的有效吗?
https://stackoverflow.com/questions/12324128
复制相似问题