pydantic-xml icon indicating copy to clipboard operation
pydantic-xml copied to clipboard

[Question] Is there any way of building xml with <![CDATA[...]]> field?

Open DLogunoff opened this issue 1 year ago • 2 comments

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 avatar Jul 19 '24 11:07 DLogunoff

@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.

dapper91 avatar Aug 24 '24 16:08 dapper91

@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>'

dapper91 avatar Sep 29 '24 16:09 dapper91