首页 > 解决方案 > 使用python解析多个xml文件

问题描述

我在一个文件夹中有多个 xml 文件。我想解析所有的 xml 文件。我尝试过 minidom 解析,但我做不到。这是xml文件就像-

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<?xml-stylesheet type="text/xsl" href="frame.xsl"?>
<frame cBy="KmG" cDate="03/05/2008 03:50:35 PST Wed" name="Abandonment" ID="2031" xsi:schemaLocation="../schema/frame.xsd" xmlns="http://framenet.icsi.berkeley.edu" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <definition>&lt;def-root&gt;An &lt;fex name="Agent"&gt;Agent&lt;/fex&gt; leaves behind a &lt;fex name="Theme"&gt;Theme&lt;/fex&gt; effectively rendering it no longer within their control or of the normal security as one's property. 

&lt;ex&gt;&lt;fex name="Agent"&gt;Carolyn&lt;/fex&gt; &lt;t&gt;abandoned&lt;/t&gt; &lt;fex name="Theme"&gt;her car&lt;/fex&gt; and jumped on a red double decker bus.&lt;/ex&gt;

&lt;ex&gt;Perhaps &lt;fex name="Agent"&gt;he&lt;/fex&gt; &lt;t&gt;left&lt;/t&gt; &lt;fex name="Theme"&gt;the key&lt;/fex&gt; in the ignition&lt;/ex&gt;

&lt;ex&gt;&lt;t&gt;Abandonment&lt;/t&gt; &lt;fex name="Theme"&gt;of a child&lt;/fex&gt; is considered to be a serious crime in many jurisdictions.&lt;/ex&gt; 
</frame>

我在下面的代码中试过这个 - 我只想在 ex.

from helperDef import *
import os
from xml.dom import minidom

for root, dirs, files in os.walk('frame'):
    for file in files:
        if (file.endswith('.xml')):
             xmldoc = minidom.parse(os.path.join(root, file))
             if '<ex>' in xmldoc:
                line = find_between(xmldoc, '<ex>', '</ex>')
                print(line)
                clean_line = cleanText(line)
                print(clean_line)

错误是 -

TypeError:“文档”类型的参数不可迭代

有什么办法吗?救命!

标签: pythonxmlparsingminidom

解决方案


我认为在 python 中解析 xml 的更好方法是使用 xmltodict

你只需要:

import xmltodict

接着:

data = xmltodict.parse(xml)

然后将您的 xml 文件转换为您可以轻松处理的 python dict。在您的情况下,您可以运行一个循环将所有文件转换为 dicts。


推荐阅读