0

我正在寻找一种将 xml 文件中可用的所有信息提取到平面文件或数据库的方法。

例如

<r>
                <P>
                    <color val="1F497D"/>
                </P>
                <t val="123" val2="234">TEST REPORT</t>
</r>

我希望这是

r
P
color,val,1f497d
t,val,123
t,val2,234

关于如何在 python 中解决这个问题的任何指示?

4

3 回答 3

1

然后安装lxml

>>> from lxml import etree
>>> parser = etree.XMLParser(remove_blank_text=True)
>>> parsed_xml = etree.XML(s,parser)
>>> for i in parsed_xml.iter('*'):
...    print i.tag
...    for x in i.items():
...       print '%s,%s' % (x[0],x[1])
...
r
P
color
val,1F497D
t
val,123
val2,234

我会留给你来格式化输出。

于 2012-10-07T06:41:44.103 回答
0

我认为你最好的选择是使用BeautifulSoup

例如(来自他们的文档):

from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)
soup.title
# <title>The Dormouse's story</title>
soup.p['class']
# u'title'
for link in soup.find_all('a'):
    print(link.get('href'))
# http://example.com/elsie
# http://example.com/lacie
# http://example.com/tillie

您还可以查看lxml,它简单高效,并且是 BeautifulSoup 的基础。具体来说,您可能想看看这个页面

于 2012-10-07T06:17:51.257 回答
0

我不确定你为什么想要这个,但你应该看看lxmlBeautifulSoup for Python。

或者,如果您只希望它完全符合您上面提供的形式:

def parse_html(html_string):
    import re
    fields = re.findall(r'(?<=\<)[\w=\s\"\']+?(?=\/?\>)', html_string)
    out = []
    for field in fields:
        tag = re.match(r'(?P<tag>\w+?) ?', field).group('tag')
        attrs = re.findall(r' (\w+?)\=[\"\'](.+?)[\"\']', field)
        if attrs:
            for x in attrs:
                out.append(','.join([tag] + list(x)))
        else:
            out.append(tag)

    print '\n'.join(out)

这有点过头了,这就是为什么您通常应该使用 lxml 或 BeautifulSoup,但它可以完成这项特定的工作。

我上面的程序的输出:

r
P
c,val,1F497D
t,val,123
t,val2,234
于 2012-10-07T06:49:33.577 回答