nested XSDs with an XML validation and to convert XML to dictionary using python

355 Views Asked by At

sample XML:

<?xml version="1.0"?>
<book>
 <to>My Readers</to>
 <from>Chaitanya</from>
 <subject>A Message to my readers</subject>
 <message>Welcome to beginnersbook.com</message>
</book>

sample XSD:

<xs:element name="book">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="to" type="xs:string"/>
      <xs:element name="from" type="xs:string"/>
      <xs:element name="subject" type="xs:string"/>
      <xs:element name="message" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>
</xs:schema>

here is the code

import xmlschema
import os
import pandas as pd
xml_file = os.path.join(os.getcwd(), 'sample.xml')
xld_file = os.path.join(os.getcwd(), 'sample.xsd')
schema = xmlschema.XMLSchema(xld_file)
if schema.is_valid(xml_file):
    try:
        my_dict = schema.to_dict(xml_file)
    except Exception as exception:
        print(exception)
else:
    print("Schema is not valid")
print(my_dict)

Here is the output
{'to': 'My Readers', 'from': 'Chaitanya', 'subject': 'A Message to my readers', 'message': 'Welcome to beginnersbook.com'}

Piece of Issue XSD(which is nested XSD):

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://services.mycccportal.com/CCC/CCCStandardEstimateWebService/EstimateTransaction" xmlns:common="http://services.mycccportal.com/CCC/CCCStandardEstimateWebService/CommonTypes" xmlns:msghdr="http://services.mycccportal.com/Interfaces/MessageHeader" targetNamespace="http://services.mycccportal.com/CCC/CCCStandardEstimateWebService/EstimateTransaction" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:import namespace="http://services.mycccportal.com/Interfaces/MessageHeader" schemaLocation="MessageHeader.xsd"/>
    <xs:import namespace="http://services.mycccportal.com/CCC/CCCStandardEstimateWebService/CommonTypes" schemaLocation="CCCEstimateCommonTypes.xsd"/>
    <xs:element name="CCCEstimateTransaction" type="CCCEstimateTransactionType"/>
    <xs:complexType name="CCCEstimateTransactionType">
        <xs:sequence>
            <xs:element name="MessageHeader" type="msghdr:MessageHeaderType"/>
            <xs:element name="Estimate" type="EstimateType"/>
        </xs:sequence>
        <xs:attribute name="Version" type="xs:string" use="required"/>
    </xs:complexType>

I am getting "Schema is not valid" for nested XSD even though I placed all XSD in same folder, not sure whether xmlschema is able to read nested XSD or not. I want xmlschema to read the nested XSDs and validate the XML with nested XSDs to convert it to dictionary.

0

There are 0 best solutions below