Python - working with xml/lxml/objectify/schemas, datatypes, and assignments

aapost aapost at idontexist.club
Wed Jan 4 12:13:47 EST 2023


On 1/4/23 09:42, Dieter Maurer wrote:
> aapost wrote at 2023-1-3 22:57 -0500:
>> ...
>> Consider the following:
>>
>>from lxml import objectify, etree
>> schema = etree.XMLSchema(file="path_to_my_xsd_schema_file")
>> parser = objectify.makeparser(schema=schema, encoding="UTF-8")
>> xml_obj = objectify.parse("path_to_my_xml_file", parser=parser)
>> xml_root = xml_obj.getroot()
>>
>> let's say I have a Version element, that is defined simply as a string
>> in a 3rd party provided xsd schema
>>
>> <xs:element name="Version" type="xs:string" minOccurs="0">
> 
> Does your schema include the third party schema?
> 
> You might have a look at `PyXB`, too.
> It tries hard to enforce schema restrictions in Python code.


Yes, to clarify, they provide the schema, which is what we use, 
downloaded locally. Basically just trying to remain compliant with their 
structures that they already define without reinventing the wheel for 
numerous calls and custom types, and in a way that feels more live 
rather than just checking validity at the end of the edits as if I were 
modifying the XML manually.

Thank you for the suggestion, PyXB works much more like how I envisioned 
working with xml in my head:

 >>> xml_root.Version = 1231.32000
pyxb.exceptions_.SimpleTypeValueError: Type 
{http://www.w3.org/2001/XMLSchema}string cannot be created from: 1231.32
 >>> xml_root.Version = "1231.32000"

I will have to do some more testing to see how smooth the transition 
back to a formatted document goes, since it creates a variable for all 
possible fields defined in the type, even if they are optional and not 
there in the situational template.

Thanks


More information about the Python-list mailing list