【问题标题】:Python minidom - Parse XML file and write to CSVPython minidom - 解析 XML 文件并写入 CSV
【发布时间】:2026-01-07 10:55:01
【问题描述】:

我正在尝试解析 XML 文件,然后将选定的检索对象写入 csv 文件。

这是我的基本 XML 文件:

<?xml version="1.0"?>
<library owner="John Q. Reader">
    <book>
        <title>Sandman Volume 1: Preludes and Nocturnes</title>
        <author>Neil Gaiman</author>
    </book>
    <book>
        <title>Good Omens</title>
        <author>Neil Gamain</author>
        <author>Terry Pratchett</author>
    </book>
    <book>
        <title>"Repent, Harlequin!" Said the Tick-Tock Man</title>
        <author>Harlan Ellison</author>
    </book>
    </book>
</library>

我用 Python 2.7 和 minidom 编写了一个基本脚本。这里是:


# Test Parser

from xml.dom.minidom import parse
import xml.dom.minidom

def printLibrary(myLibrary):
    books = myLibrary.getElementsByTagName("book")
    for book in books:
        print "*****Book*****"
        print "Title: %s" % book.getElementsByTagName("title")[0].childNodes[0].data
        a = for author in book.getElementsByTagName("author"):
            print "Author: %s" % author.childNodes[0].data
            a.csv.writer()
doc = parse('library.xml')
myLibrary = doc.getElementsByTagName("library")[0]

# Get book elements in library
books = myLibrary.getElementsByTagName("book")

# Print each book's title
printLibrary(myLibrary)

到目前为止,在 Win7 中从命令行运行此脚本时,会显示每本书的书名和作者。

我想要将这些结果输出到 csv 文件,所以它看起来像这样:

标题,作者 标题,作者 标题,作者 标题,作者 标题,作者 等等

但是,我无法让它工作 - 我对 Python 还很陌生,我从事 IT 和 SQL 工作,而基本编程是我的工作。

任何帮助将不胜感激!

【问题讨论】:

  • Sandman Volume 1: Preludes and Nocturnes Neil GaimanGood Omens Neil GamainTerry Pratchett"忏悔吧,小丑!”滴答声人说 Harlan Ellison
  • 对不起,我在这里发布的 XML 文件没有格式化,我看不出如何使它看起来漂亮,带有缩进等。
  • 你还能显示示例输出吗?因为从问题中不清楚。
  • 你试过使用 csv 模块吗?

标签: python xml csv minidom


【解决方案1】:

使用csv 模块。

# Test Parser

from xml.dom.minidom import parse
import csv 


def writeToCSV(myLibrary):
    csvfile = open('output.csv', 'w')
    fieldnames = ['title', 'author']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()

    books = myLibrary.getElementsByTagName("book")
    for book in books:
        titleValue = book.getElementsByTagName("title")[0].childNodes[0].data
        for author in book.getElementsByTagName("author"):
            authorValue = author.childNodes[0].data
            writer.writerow({'title': titleValue, 'author': authorValue})

doc = parse('library.xml')
myLibrary = doc.getElementsByTagName("library")[0]

# Get book elements in library
books = myLibrary.getElementsByTagName("book")

# Print each book's title
writeToCSV(myLibrary)

输出文件:

title,author
Sandman Volume 1: Preludes and Nocturnes,Neil Gaiman
Good Omens,Neil Gamain
Good Omens,Terry Pratchett
"""Repent, Harlequin!"" Said the Tick-Tock Man",Harlan Ellison

【讨论】:

  • 非常感谢 - 这非常有效。现在我需要在一个更复杂的 XML 文件上尝试这个并添加更多元素!