for index in rootless:
if rootless[index] is not None:
rootless[index] = "<![CDATA[" + str(rootless[index]) + "]]>"
params_xml = xmltodict.unparse(rootless)
tried adding to array before parse but it escapes special char resulting
<city><;[CDATA[new york]]></city><state><;[CDATA[NY]]></state><zip><![CDATA[10036]]></zip><phone></phone>
what i am looking for is
<city><![CDATA[new york]]></city><state><![CDATA[NY]]></state><zip><![CDATA[10036]]></zip><phone></phone>
I can technically regex >
and </
into text above but there probably a better way to do this
the rootless looks likes this
{
"city": "new york",
"state": "NY",
"zip": 10036,
"phone": ""
}
Without getting into the structure of your dictionary, etc., here's a way to get your CDATA properly inserted.
Let's assume that your NYC address and xml are like this:
nyc = ["New York", "NY","10036"]
my_xml ="""<entry><city></city><state></state><zip></zip></entry>"""
In that case, you need to:
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())
edit:
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())
Output:
<entry><city><![CDATA[new york]]></city><state><![CDATA[NY]]></state><zip><![CDATA[10036]]></zip><phone><![CDATA[]]></phone></entry>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.