首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用lxml.objectify多次追加相同的XML元素

如何使用lxml.objectify多次追加相同的XML元素
EN

Stack Overflow用户
提问于 2012-09-08 03:18:47
回答 2查看 2.2K关注 0票数 0

我尝试使用lxml.objectify package重新创建以下XML

代码语言:javascript
复制
<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元素。基本上,我有以下不能工作的代码:

代码语言:javascript
复制
    # 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中只输出电话信息的一部分。有谁有什么想法吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-09-08 04:15:47

您应该创建objectify.Element对象,并将它们添加为root.customers的子对象。

例如,可以像这样插入两个电话号码:

代码语言:javascript
复制
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,请执行以下操作:

代码语言:javascript
复制
from lxml import etree
# ...
objectify.deannotate(root, xsi_nil=True)
etree.cleanup_namespaces(root)

)

票数 1
EN

Stack Overflow用户

发布于 2012-09-08 04:21:42

下面是一些使用objectify E-Factory构造XML的示例代码

代码语言:javascript
复制
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))

我在这里对其进行了硬编码,但您可以将其转换为数据上的循环。这对你的目的有效吗?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12324128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档