【发布时间】:2017-08-20 20:03:22
【问题描述】:
我有一个 10 GB 的 xml 文件,其中包含不同块的列表。这是我的文件的 sn-p:
<image>
<ref>www.test.com</ref>
<label/>
<number>0</number>
<ID>ID0</ID>
<name>test1</name>
<comment>
<line number="0">This is a comment</line>
<line number="1">This is also another comment</line>
</comment>
<creationDate>2017-02-13T15:46:16-04:00</creationDate>
</image>
<result>
<ref>www.test1.com</ref>
<label/>
<number>001</number>
<ID>RE1</ID>
<name>test2</name>
<comment>
<line number="0">This is a comment2</line>
</comment>
<creationDate>2017-01-13T15:46:16-04:00</creationDate>
</result>
<image>
<ref>www.test3.com</ref>
<label/>
<number>1</number>
<ID>ID1</ID>
<value>10030</value>
<name>test3</name>
<comment>
<line number="0">This is a comment3</line>
</comment>
<creationDate>2017-04-13T15:46:16-04:00</creationDate>
</image>
所以我的目标是使用 celementtree 的 iterparse 以序列化模式解析我的文件,但想一次获取每个块。例如,我喜欢获取整个 image 块,然后解析该块内的值。
例如,我需要获取第一个图像块 (*<image>... </image>*) 块,然后在其中打印 www.test.com、0、id0、test1 的值,这是一个注释和 2017-02-13T15: 46:16-04:00。
所以我使用了以下代码,但它似乎只能逐行读取 xml 文件,也无法打印每行或元素内的值:
for event, element in ET.iterparse(pathtofile):
print element.tag , element.attrib
你能帮我解决这个问题吗?我对 xml 解析完全陌生。 我还想将每个解析的块转换为 python 中的字典。有可能吗?
【问题讨论】:
标签: python xml parsing xml-parsing