Package: xml-dataclasses
XML dataclassesXML dataclasses on PyPIThis library maps XML to and from Python dataclasses. It build on normal dataclasses from the standard library and useslxmlfor parsing/generating XML.It's currently in alpha. It isn't ready for production if you aren't willing to do your own evaluation/quality assurance.Requires Python 3.7 or higher.FeaturesConvert XML documents to well-defined dataclasses, which work with Mypy or IDE auto-completionXML dataclasses are dataclassesFull control of parsing and generating XML vialxmlLoading and dumping of attributes, child elements, and text contentRequired and optional attributes/child elementsLists of child elements are supported, as are unions and lists or unionsInheritance does work, but has the same limitations as dataclasses. Inheriting from base classes with required fields and declaring optional fields doesn't work due to field order. This isn't recommendedNamespace support is decent as long as correctly declared. I've tried on several real-world examples, although they were known to be valid.lxmldoes a great job at expanding namespace information when loading and simplifying it when savingPost-load validation hookxml_validateFields not required in the constructor are ignored by this library (viaignored()orinit=False)LimitationsWhitespace and comments aren't supported in the data model. They must be stripped when loading the XMLSo far, I haven't found any examples where XML can't be mapped to a dataclass, but it's likely possible given how complex XML isNo typing/type conversions. Since XML is untyped, only string values are currently allowed. Type conversions are tricky to implement in a type-safe and extensible manner.Dataclasses must be written by hand, no tools are provided to generate these from, DTDs, XML schema definitions, or RELAX NG schemasSecurityThe caveats concerning untrusted content are roughly the same as withlxml, since that does the parsing. This is good, sincelxml's behaviour to XML attacks are well-understood. This library recursively resolves data structures, which may have memory implications for unbounded payloads. Because loading is driven from the dataclass definitions, it shouldn't be possible to execute arbitrary Python code (not a guarantee, see license). If you must deal with untrusted content, a workaround is touselxmlto validateuntrusted content with a strict schema, which you may already be doing.PatternsDefining attributesAttributes can be eitherstrorOptional[str]. Using any other type won't work. Attributes can be renamed or have their namespace modified via therenamefunction. It can be used either on its own, or with an existing field definition:@xml_dataclassclassFoo:__ns__=Nonerequired:stroptional:Optional[str]=Nonerenamed_with_default:str=rename(default=None,name="renamed-with-default")namespaced:str=rename(ns="http://www.w3.org/XML/1998/namespace")existing_field:str=rename(field(...),name="existing-field")For now, you can work around this limitation with properties that do the conversion, and perform post-load validation.By default, unknown attributes raise an error. This can be disabled by passingOptionstoloadwithignore_unknown_attributes.Defining textLike attributes, text can be eitherstrorOptional[str]. You must declare text content with thetextfunction. Similar torename, this function can use an existing field definition, or take thedefaultargument. Text cannot be renamed or namespaced. Every class can only have one field defining text content. If a class has text content, it cannot have any children.@xml_dataclassclassFoo:__ns__=Nonevalue:str=text()@xml_dataclassclassFoo:__ns__=Nonecontent:Optional[str]=text(default=None)@xml_dataclassclassFoo:__ns__=Noneuuid:str=text(field(default_factory=lambda:str(uuid4())))Defining children/child elementsChildren must ultimately be other XML dataclasses. However, they can also beOptional,List, andUniontypes:Optionalmust be at the top level. Valid:Optional[List[XmlDataclass]]. Invalid:List[Optional[XmlDataclass]]Next,Listshould be defined (if multiple child elements are allowed). Valid:List[Union[XmlDataclass1, XmlDataclass2]]. Invalid:Union[List[XmlDataclass1], XmlDataclass2]Finally, ifOptionalorListwere used, a union type should be the inner-most (again, if needed)If a class has children, it cannot have text content.Children can be renamed via therenamefunction. However, attempting to set a namespace is invalid, since the namespace is provided by the child type's XML dataclass. Also, unions of XML dataclasses must have the same namespace (you can use different fields with renaming if they have different namespaces, since the XML names will be resolved as a combination of namespace and name).By default, unknown children raise an error. This can be disabled by passingOptionstoloadwithignore_unknown_children.Defining post-load validationSimply implement an instance method calledxml_validatewith no parameters, and no return value (if you're using type hints):defxml_validate(self)->None:passIf defined, theloadfunction will call it after all values have been loaded and assigned to the XML dataclass. You can validate the fields you want inside this method. Return values are ignored; instead raise and catch exceptions.Ignored fieldsFields not required in the constructor are ignored by this library (new in version 0.0.6). This is useful if you want to populate a field via post-load validation.You can simply setinit=False, although you may also want to exclude the field from comparisons. Theignoredfunction does this, and can also be used.The name doesn't matter, but it might be useful to use the_prefix as a convention.Example (fully type hinted)(This is a simplified real world example - the container can also include optionallinkschild elements.)<?xml version="1.0"?><containerversion="1.0"xmlns="urn:oasis:names:tc:opendocument:xmlns:container"><rootfiles><rootfilefull-path="OEBPS/content.opf"media-type="application/oebps-package+xml"/></rootfiles></container>fromdataclassesimportdataclassfromtypingimportListfromlxmlimportetree# type: ignorefromxml_dataclassesimportxml_dataclass,rename,load,dump,NsMap,XmlDataclassCONTAINER_NS="urn:oasis:names:tc:opendocument:xmlns:container"@xml_dataclass@dataclassclassRootFile:__ns__=CONTAINER_NSfull_path:str=rename(name="full-path")media_type:str=rename(name="media-type")@xml_dataclass@dataclassclassRootFiles:__ns__=CONTAINER_NSrootfile:List[RootFile]# see Gotchas, this workaround is required for type hinting@xml_dataclass@dataclassclassContainer(XmlDataclass):__ns__=CONTAINER_NSversion:strrootfiles:RootFiles# WARNING: this is an incomplete implementation of an OPF containerdefxml_validate(self)->None:ifself.version!="1.0":raiseValueError(f"Unknown container version '{self.version}'")if__name__=="__main__":nsmap:NsMap={None:CONTAINER_NS}# see Gotchas, stripping whitespace and comments is highly recommendedparser=etree.XMLParser(remove_blank_text=True,remove_comments=True)lxml_el_in=etree.parse("container.xml",parser).getroot()container=load(Container,lxml_el_in,"container")lxml_el_out=dump(container,"container",nsmap)print(etree.tostring(lxml_el_out,encoding="unicode",pretty_print=True))GotchasType hintingThis can be a real pain to get right. Unfortunately, if you need this, you may have to resort to:@xml_dataclass@dataclassclassChild:__ns__=Nonepass@xml_dataclass@dataclassclassParent(XmlDataclass):__ns__=Nonechildren:ChildIt's important that@dataclassbe thelastdecorator, i.e. the closest to the class definition (and so the first to be applied). Luckily, only the root class you intend to pass toload/dumphas to inherit fromXmlDataclass, but all classes should have the@dataclassdecorator applied.Whitespace and commentsIf you are able to, it is strongly recommended you strip whitespace and comments from the input vialxml:parser=etree.XMLParser(remove_blank_text=True,remove_comments=True)By default,lxmlpreserves whitespace. This can cause a problem when checking if elements have no text. The library does attempt to strip these; literally via Python'sstrip(). Butlxmlis likely faster and more robust.Similarly, comments are included by default, and because loading is strict, they will be considered as nodes that the dataclass has not declared. It is recommended to omit them during parsing.Optional vs requiredOn dataclasses, optional fields also usually have a default value to be useful. But this isn't required;Optionalis just a type hint to sayNoneis allowed. This would occur e.g. if an element has no children.For loading XML dataclasses, whether or not a field is required is determined by if it has adefault/default_factorydefined. If so, and it's missing, that default is used. Otherwise, an error is raised.For dumping, the default isn't considered. Instead, if a value is marked asOptionaland the value isNone, it isn't written.This makes sense in many cases, but possibly not every case.Changelog[0.0.9] - 2022-02-10Fix issue passing options when loading children - thankstim-lansen![0.0.7] and [0.0.8] - 2021-04-08Warn if comments are found/don't treat comments as child elements in error messagesAllow lenient loading of undeclared attributes or children[0.0.6] - 2020-03-25Allow ignored fields viainit=falseor theignoredfunction[0.0.5] - 2020-02-18Fixed type hinting for consumers. While the library passed mypy validation, it was hard to get XML dataclasses in a codebase to pass mypy validation[0.0.4] - 2020-02-16Improved type resolving. This lead to easier field definitions, asattrandchildare no longer needed because the type of the field is inferred[0.0.3] - 2020-02-16Added support for union types on childrenDevelopmentThis project usespre-committo run some linting hooks when committing. When you first clone the repo, please run:pre-commit installYou may also run the hooks at any time:pre-commit run --all-filesDependencies are managed viapoetry. To install all dependencies, use:poetry installThis will also install development dependencies such asblack,isort,pylint,mypy, andpytest. Pre-defined tasks make it easy to run these, for examplepoetry run task lint- this runsblack,isort,mypy, andpylintpoetry run task test- this runspytestwith coverageFor a full list of tasks, seepoetry run task --list.LicenseThis library is licensed under the Mozilla Public License Version 2.0. For more information, seeLICENSE.