在单独的txt文件中提取每个xml节点

时间:2014-09-03 14:01:22

标签: python python-2.7

我有一个像这样的xml文件:

<root>
    <article>
        <article_taxonomy></article_taxonomy>
        <article_place>Somewhere</article_place>
        <article_number>1</article_number>
        <article_date>2001</article_date>
        <article_body>Blah blah balh</article_body>
    </article>

    <article>
        <article_taxonomy></article_taxonomy>
        <article_place>Somewhere</article_place>
        <article_number>2</article_number>
        <article_date>2001</article_date>
        <article_body>Blah blah balh</article_body>
    </article>

    ...
    ...
    more nodes

</root> 

我要做的是将每个节点(从<article> to </article>标签)提取并写入单独的txt或xml文件。我也想保留标签。

没有正则表达式可以做到吗?有什么建议吗?

2 个答案:

答案 0 :(得分:1)

以下是使用ElementTree执行此操作的一种方法:

import xml.etree.ElementTree as ElementTree

def main():
    with open('data.xml') as f:
        et = ElementTree.parse(f)
        for article in et.findall('article'):
            xml_string = ElementTree.tostring(article)
            # Now you can write xml_string to a new file
            # Take care to name the files sequentially

if __name__ == '__main__':
    main()

答案 1 :(得分:0)

尝试这样的事情:

from xml.dom import minidom
xmlfile = minidom.parse('yourfile.xml')
#for example for 'article_body'
article_body = xmlfile.getElementsByTagName('article_body') 

import xml.etree.ElementTree as ET
xmlfile = ET.parse('yourfile.xml')
root_tag = xmlfile.getroot()
for each_article in root_tag.findall('article'):
   article_taxonomy = each_article.find('article_taxonomy').text
   article_place = each_article.find('article_place').text
   # etc etc