使用XML验证的嵌套XSD,并使用python将XML转换为字典

使用XML验证的嵌套XSD,并使用python将XML转换为字典,python,python-xmlschema,Python,Python Xmlschema,示例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> </b

示例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>
这是输出
{'to':'My Readers','from':'Chaitanya','subject':'A Message to My Readers','Message':'Welcome to neighters book.com'}

问题部分XSD(嵌套XSD):


对于嵌套的XSD,即使我将所有XSD放在同一个文件夹中,也会得到“Schema无效”,不确定xmlschema是否能够读取嵌套的XSD。我希望xmlschema读取嵌套的XSD,并使用嵌套的XSD验证XML,以将其转换为字典。

“Schema无效”是非常明确的,因为错误消息是这样的。Schema.is_valid(XML_文件)给了我false,所以它将转到其他部分并给出打印输出
<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>
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)
<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>