首页 > 解决方案 > Python使用CDATA将数组转换为xml

问题描述

    for index in rootless:
        if rootless[index] is not None:
            rootless[index] = "<![CDATA[" + str(rootless[index]) + "]]>"

    params_xml = xmltodict.unparse(rootless)

尝试在解析之前添加到数组,但它转义了特殊的字符

<city>&lt;![CDATA[new york]]&gt;</city><state>&lt;![CDATA[NY]]&gt;</state><zip>&lt;![CDATA[10036]]&gt;</zip><phone></phone>

我要找的是

<city><![CDATA[new york]]></city><state><![CDATA[NY]]></state><zip><![CDATA[10036]]></zip><phone></phone>

我可以在技术上正则表达式></上面的文本,但可能有更好的方法来做到这一点

无根的看起来像这样

{
"city": "new york",
"state": "NY",
"zip": 10036,
"phone": ""
}

标签: pythonxml

解决方案


在不涉及字典结构等的情况下,这是一种正确插入 CDATA 的方法。

假设您的纽约地址和 xml 如下所示:

nyc = ["New York", "NY","10036"]
my_xml ="""<entry><city></city><state></state><zip></zip></entry>"""

在这种情况下,您需要:

from lxml import etree
doc = etree.fromstring(my_xml)
for a, b in zip(nyc,doc.xpath('/entry/*')):   
    b.text = etree.CDATA(a)
etree.tostring(doc).decode())

编辑:

items = {
"city": "new york",
"state": "NY",
"zip": 10036,
"phone": ""
}
my_xml ="""<entry><city></city><state></state><zip></zip><phone></phone></entry>"""

doc = etree.fromstring(my_xml)

for a, b in zip(list(items.values()),doc.xpath('/entry/*')):   
    b.text = etree.CDATA(str(a))
print(etree.tostring(doc).decode())

输出:

<entry><city><![CDATA[new york]]></city><state><![CDATA[NY]]></state><zip><![CDATA[10036]]></zip><phone><![CDATA[]]></phone></entry>

推荐阅读