我希望能够"走路"使用Python 3中的lxml嵌套的XSD

时间:2017-02-22 15:41:18

标签: python xsd lxml

我知道如何使用Python 3使用lxml来运行基本的XSD

#!/usr/bin/python

#
# Go through an XSD, listing attributes and entities
#

import argparse
from lxml import etree

def do_element(elmnt):
     nam = elmnt.get('name')
     if len(elmnt) != 0:
        # Entity
        print("Entity: ", nam, " Type: ",elmnt.get('type','None'))
     else:
        # Attribute
        if nam != None:
             print("Attrib: ", nam, " Type: ",elmnt.get('type','None') )

def main():
    parser = argparse.ArgumentParser(prog='test')
    parser.add_argument('-d',action='store_true',help='debugging')

    parser.add_argument('infile')
    args = parser.parse_args()

    xsd_prs = etree.XMLParser(remove_blank_text=True)
    xsd_doc = etree.parse(args.infile, xsd_prs)
    xsd_doc.xinclude()

    walkall = xsd_doc.getiterator()
    for elmnt in walkall:
        do_element(elmnt)

if __name__ == "__main__":
    main()

为输入的XSD的每个标签调用do_element,后者又会发出一些有关属性的数据。问题是当我有一个带导入的XSD(在我当前的目录中)时:

AAA.xsd:

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema 
   elementFormDefault="qualified"
   targetNamespace="AAA"
   version="1"
   xmlns:xs="http://www.w3.org/2001/XMLSchema"
   xmlns:AAA="AAA"
   xmlns:BBB="BBB">
   <xs:import namespace="BBB" schemaLocation="BBB.xsd"/>
   <xs:element name="StringAttribute" type="xs:string">
   </xs:element>
   <xs:element name="ComplexEntity" type="BBB:ComplexEntityType">
   </xs:element>
</xs:schema>

和BBB.xsd:

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema 
   elementFormDefault="qualified"
   targetNamespace="BBB"
   xmlns:BBB="BBB"
   xmlns:xs="http://www.w3.org/2001/XMLSchema">
   <xs:complexType name="ComplexEntityType">
       <xs:sequence>
         <xs:element name="NestedString" type="xs:string">
         </xs:element>
      </xs:sequence>   
   </xs:complexType>
</xs:schema>

我希望通过运行文件文件:AAA.xsd,我可以将定义移到命名空间BBB中。它并没有发生。它到达元素Item但不会在BBB.xsd中定义的ComplexType中进一步分解。我尝试按如下方式解析xsd_doc:

xsd_doc = etree.parse(args.infile)
xsd = etree.XMLSchema(xsd_doc)

和lxml爆炸:

lxml.etree.XMLSchemaParseError: Element '{http://www.w3.org/2001/XMLSchema}element', attribute 'type': References from this schema to components in the namespace 'subtypes' are not allowed, since not indicated by an import statement., line 35

进口绝对存在。为什么不遵循它?

0 个答案:

没有答案