pydantic-xml
pydantic-xml copied to clipboard
[Question] Is there any way of building xml with <![CDATA[...]]> field?
Hi. I'm using pydantic-xml to build xml files from json. I faced a problem. I need to add a value and I tried to do it manually, simply using f-strings. But after xml_model.to_xml() my < and > is being replaced by < and >
How can I avoid it?
@DLogunoff Hi
right now CDATA is not supported by the library since it is not supported by xml.etree library. I am going to add it for lxml backend only in the next version.
@DLogunoff as a temporary solution you could use custom serializer:
>>> from pydantic_xml import BaseXmlModel, xml_field_serializer
>>> from pydantic_xml.element import XmlElementWriter
>>>
>>> from lxml.etree import CDATA
>>>
>>> class Content(BaseXmlModel, tag='content'):
... text: str
...
... @xml_field_serializer('text')
... def serialize_text(self, element: XmlElementWriter, value: str, field_name: str) -> None:
... element.set_text(CDATA(value))
...
>>> content = Content(text='<html></html>')
>>>
>>> print(content.to_xml())
b'<content><![CDATA[<html></html>]]></content>'