McMendel
McMendel

Reputation: 115

Validate Python classes created from generateDS

I have several XSDs that change sometimes.

I used to write my XML files hard-coded, so every time that the XSD was changed, I had to search for the XML files that were dependent on that XSD.

That's why I moved to generateDS (Version 2.15b).

I wrote a script using generateDS, so that every time the XSD is changed, the genereateDS script will run and generate classes.

The classes generated are used as a "structures" for me to check if the XML fits.

For example, if I have this as my XSD:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
       xmlns:tns="http://tempuri.org/PurchaseOrderSchema.xsd"
       targetNamespace="http://tempuri.org/PurchaseOrderSchema.xsd"
       elementFormDefault="qualified">

   <xsd:element name="PurchaseOrder" type="tns:PurchaseOrderType"/>
   <xsd:complexType name="PurchaseOrderType">
       <xsd:sequence>
           <xsd:element name="ShipTo" type="tns:USAddress" maxOccurs="2"/>
           <xsd:element name="BillTo" type="tns:USAddress"/>
       </xsd:sequence>
       <xsd:attribute name="OrderDate" type="xsd:date"/>
   </xsd:complexType>

   <xsd:complexType name="USAddress">
       <xsd:sequence>
           <xsd:element name="name"   type="xsd:string"/>
           <xsd:element name="street" type="xsd:string"/>
           <xsd:element name="city"   type="xsd:string"/>
           <xsd:element name="state"  type="xsd:string"/>
           <xsd:element name="zip"    type="xsd:integer"/>
       </xsd:sequence>
       <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
    </xsd:complexType>
</xsd:schema>

and I'm creating this class:

us = orders_api.USAddress(state = "NY")
pot = orders_api.PurchaseOrderType(BillTo = us,
                           OrderDate=datetime.datetime.now())

Is there a way to validate the instance (pot) with the XSD? (for this example, pot is not a valid xml, because it has no 'ShipTo' element, us has no 'country' attribute and another elements)

Upvotes: 1

Views: 911

Answers (1)

Adi Ep
Adi Ep

Reputation: 805

You can validate XML is valid with an XSD schema:

import xmlschema

schema = xmlschema.XMLSchema(original_full_path)

# Check XML is valid with an XSD file:
is_valid = schema.is_valid(original_full_path)
log.warning("is_valid: {}".format(is_valid))

Upvotes: 0

Related Questions