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

2024-06-08 07:50:42 发布

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

我有一个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>

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

^{pr2}$

这段代码在第2行出错:xml.etree.ElementTree.ParseError: junk after document element:

我想这是因为有多个xml标记,你知道吗,我应该如何解析它?在


Tags: name标记dataversionxmlyearcountryrank
3条回答

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

代码监视“累积的”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']

Question: ... any idea, how should i parse this?

过滤整个文件并拆分为有效的<?xml ...块。
创建myfile_01, myfile_02 ... myfile_nn。在

n = 0
out_fh = None
with open('myfile.xml') as in_fh:
    while True:
        line = in_fh.readline()
        if not line: break

        if line.startswith('<?xml'):
            if out_fh:
                out_fh.close()
            n += 1
            out_fh = open('myfile_{:02}'.format(n))

        out_fh.write(line)

    out_fh.close()

如果您希望所有<country>在一个XML Tree中:

^{pr2}$

用Python:3.4.2测试

我使用了一个简单的技巧来解析这种伪XML(Wazuh rule files)来说明它的重要性——只是暂时将它包装在一个伪元素<whatever></whatever>中,从而在所有这些“根”上形成一个根。在

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

<data> ... </data>
<data> ... </data>

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

^{pr2}$

然后像往常一样解析它并迭代<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 ...

相关问题 更多 >