Validating and populating default values ​​in XSD-based XML in Python

How to populate the default value in my XML during XSD validation? If my attribute is not defined as use="require" and has default="1" , it would be possible to populate these default values ​​from XSD to XML.

Example: Original XML:

 <a> <b/> <bc="2"/> </a> 

XSD Schema:

 <xs:element name="a"> <xs:complexType> <xs:sequence> <xs:element name="b" maxOccurs="unbounded"> <xs:attribute name="c" default="1"/> </xs:element> </xs:sequence> </xs:complexType> </xs:element> 

I want to check the source XML using XSD and populate all the default values:

 <a> <bc="1"/> <bc="2"/> </a> 

How do I get it in Python? There are no problems during validation (for example, XMLSchema). The problem is the default values.

+3
source share
1 answer

To follow my comment, here is the code

 from lxml import etree from lxml.html import parse schema_root = etree.XML('''\ <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="a"> <xs:complexType> <xs:sequence> <xs:element name="b" maxOccurs="unbounded"> <xs:complexType> <xs:attribute name="c" default="1" type="xs:string"/> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>''') xmls = '''<a> <b/> <bc="2"/> </a>''' schema = etree.XMLSchema(schema_root) parser = etree.XMLParser(schema = schema, attribute_defaults = True) root = etree.fromstring(xmls, parser) result = etree.tostring(root, pretty_print=True, method="xml") print result 

will provide you

 <a> <bc="1"/> <bc="2"/> </a> 

I changed your XSD a bit, wrapped xs:attribute in xs:complexType and added a schema namespace. To fill in your default values, you need to pass attribute_defaults=True to etree.XMLParser() and it should work.

+3
source

Source: https://habr.com/ru/post/1337085/


All Articles