在python中解析具有多个根元素的xml文件

ggu*_*pta 6 python xml parsing python-2.7

我有一个xml文件,我需要从文件中获取一些标记以供某些使用,其数据如下:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
<?xml version="1.0"?>
<data>
    <country name="Liechtenstein1">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria1" direction="E"/>
        <neighbor name="Switzerland1" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia1" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
Run Code Online (Sandbox Code Playgroud)

我需要解析这个,所以我用了:

import xml.etree.ElementTree as ET
tree = ET.parse("myfile.xml")
root = tree.getroot()
Run Code Online (Sandbox Code Playgroud)

此代码在第2行给出了错误: xml.etree.ElementTree.ParseError: junk after document element:

我认为这是因为多个xml标记,您有什么主意,该如何解析?

kra*_*etz 7

我曾经用一个简单的技巧来解析这种伪 XML(Wazuh 规则文件,因为它很重要) - 只是暂时将它包装在一个假元素中,<whatever></whatever>从而在所有这些“根”上形成一个单一的根。

在您的情况下,而不是像这样使用无效的 XML:

<data> ... </data>
<data> ... </data>
Run Code Online (Sandbox Code Playgroud)

就在将其传递给解析器之前,暂时将其重写为:

<whatever>
    <data> ... </data>
    <data> ... </data>
</whatever>
Run Code Online (Sandbox Code Playgroud)

然后像往常一样解析它并迭代<data>元素。

import xml.etree.ElementTree as etree
import pathlib

file = Path('rules/0020-syslog_rules.xml')
data = b'<rules>' + file.read_bytes() + b'</rules>'
etree.fromstring(data)
etree.findall('group')
... array of Elements ...
Run Code Online (Sandbox Code Playgroud)


Bil*_*ell 4

如果您需要,此代码将填充一种方法的详细信息。

该代码监视“accumulated_xml”,直到遇到另一个 xml 文档的开头或文件的末尾。当它拥有完整的 xml 文档时,它会display调用lxml库来解析该文档并报告一些内容。

>>> from lxml import etree
>>> def display(alist):
...     tree = etree.fromstring(''.join(alist))
...     for country in tree.xpath('.//country'):
...         print(country.attrib['name'], country.find('rank').text, country.find('year').text)
...         print([neighbour.attrib['name'] for neighbour in country.xpath('neighbor')])
... 
>>> accumulated_xml = []
>>> with open('temp.xml') as temp:
...     while True:
...         line = temp.readline()
...         if line:
...             if line.startswith('<?xml'):
...                 if accumulated_xml:
...                     display (accumulated_xml)
...                     accumulated_xml = []
...             else:
...                 accumulated_xml.append(line.strip())
...         else:
...             display (accumulated_xml)
...             break
... 
Liechtenstein 1 2008
['Austria', 'Switzerland']
Singapore 4 2011
['Malaysia']
Panama 68 2011
['Costa Rica', 'Colombia']
Liechtenstein1 1 2008
['Austria1', 'Switzerland1']
Singapore 4 2011
['Malaysia1']
Panama 68 2011
['Costa Rica', 'Colombia']
Run Code Online (Sandbox Code Playgroud)