Python xml etree DTD from a StringIO source?

前端 未结 2 966
日久生厌
日久生厌 2021-01-06 09:23

I\'m adapting the following code (created via advice in this question), that took an XML file and it\'s DTD and converted them to a different format. For this problem only t

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-06 09:35

    Here's a short but complete example, using the custom resolver technique @Steven mentioned.

    from StringIO import StringIO
    from lxml import etree
    
    data = dict(
        xml_file = '''
    
    ézz
    ''',
        dtd_file = '''
    
    
    ''')
    
    class DTDResolver(etree.Resolver):
         def resolve(self, url, id, context):
             return self.resolve_string(data['dtd_file'], context)
    
    xmldoc = StringIO(data['xml_file'])
    parser = etree.XMLParser(dtd_validation=True, load_dtd=True)
    parser.resolvers.add(DTDResolver())
    try:
        tree = etree.parse(xmldoc, parser)
    except etree.XMLSyntaxError as e:
        # handle xml and validation errors
    

提交回复
热议问题