如何检测xml的起始标签并进行解析和对象化

2024-09-19 23:31:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用lxml来解析和对象化路径中的xml文件,我有很多模型和xsd,每个对象模型都映射到特定的定义类,例如,如果xml以model标记开头,那么它就是一个dataModel,如果它以page tag开头,那么它就是viewModel。在

我的问题是如何有效地检测xml文件从哪个标记开始,然后用适当的xsd文件解析它,然后将其对象化

files = glob(os.path.join('resources/xml', '*.xml'))
for f in files:
    xmlinput = open(f)
    xmlContent = xmlinput.read()

    if xsdPath:
        xsdFile = open(xsdPath)
        # xsdFile should retrieve according to xml content
        schema = etree.XMLSchema(file=xsdFile)

        xmlinput.seek(0)
        myxml = etree.parse(xmlinput)

        try:
            schema.assertValid(myxml)

        except etree.DocumentInvalid as x:
            print "In file %s error %s has occurred." % (xmlPath, x.message)
        finally:
            xsdFile.close()

    xmlinput.close()

Tags: 文件标记模型schemafilesxmlopenfile
1条回答
网友
1楼 · 发布于 2024-09-19 23:31:39

我自愿放弃阅读和治疗文件,集中精力解决你的问题:

>>> from lxml.etree import fromstring
>>> # We have XMLs with different root tag
>>> tree1 = fromstring("<model><foo/><bar/></model>")
>>> tree2 = fromstring("<page><baz/><blah/></page>")
>>>
>>> # We have different treatments
>>> def modelTreatement(etree):
...     return etree.xpath('//bar')
...
>>> def pageTreatment(etree):
...     return etree.xpath('//blah')
...
>>> # Here is a recipe to read the root tag
>>> tree1.getroottree().getroot().tag
'model'
>>> tree2.getroottree().getroot().tag
'page'
>>>
>>> # So, by building an appropriated dict :
>>> tag_to_treatment_map = {'model': modelTreatement, 'page': pageTreatment}
>>> # You can run the right method on the right tree
>>> for tree in [tree1, tree2]:
...     tag_to_treatment_map[tree.getroottree().getroot().tag](tree)
...
[<Element bar at 0x24979b0>]
[<Element blah at 0x2497a00>]

希望这对某人有用,即使我之前没看过。在

相关问题 更多 >