python - 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><![CDATA[new york]]></city><state><![CDATA[NY]]></state><zip><![CDATA[10036]]></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": ""
}
解决方案
在不涉及字典结构等的情况下,这是一种正确插入 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>
推荐阅读
- bash - 如何根据另一个变量的值更新 dockerfile 中的变量?
- c++ - C++ SLList - 从堆中删除临时节点?
- python-3.x - 如何使用 tkinter 创建带有时间值的输出框
- json - NiFi:将属性合并到流文件的 JSON 内容中(不覆盖整个流文件)
- scala - Scala列表的唯一最大元素
- bash - 为什么我不能在权限为 000 的文件上使用 `$ sudo echo "hello" > file`?
- python-3.x - 如何将转换逻辑应用于字典中给定键的值
- homebrew - How can I maintain consistency between my linux shell environment and macos using homebrew?
- machine-learning - Epsilon 贪心 q 学习中的 Epsilon 和学习率衰减
- ios - NotificationCenter 是否有 didUnlockDevice 事件?