Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
DLogunoff opened this issue Jul 19, 2024 · 2 comments
Open
Labels
enhancement New feature or request

Comments

@DLogunoff
Copy link

DLogunoff commented Jul 19, 2024

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?

@dapper91
Copy link
Owner

@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 dapper91 added the enhancement New feature or request label Aug 24, 2024
@dapper91
Copy link
Owner

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants