使用xml.dom.minidom从Mysql XML转储中提取数据

时间:2012-04-18 01:04:53

标签: python mysql xml dom minidom

我使用phpmyadmin将一个mysql数据库导出到xml,现在我想用minidom解析它,但是我无法以我需要的形式获取内容。

摘要:我需要将变量title分配给<column name="news_title">This is the title</column>

中包含的文字

提取的db看起来像这样:

<pma_xml_export version="1.0" >
    <database name="dbname">
        <!-- Table newsbox -->
        <table name="newsbox">
            <column name="news_id">1</column>
            <column name="news_title">This is the title</column>
            <column name="news_text">This is the news text</column>
            <column name="date">Thu, 28 Feb 2008 20:10:30 -0500</column>
            <column name="author">author</column>
            <column name="category">site_announcement</column>
        </table>
    </database>
</pma_xml_export>

我可以使用以下脚本提取文本,但它不是我需要的格式:

doc = parseString(document)

pmaexport = doc.getElementsByTagName("pma_xml_export")[0]
columns = pmaexport.getElementsByTagName("column")


for item in columns:
    name = item.getAttribute("name")
    text = item.firstChild.data.strip()
    print name, text

我需要的是可以将这些元素的文本内容分配给可以传递的变量的东西,例如,

for item in columns:
    title = ???
    text = ???
    date = ???
    author = ???

如果db输出采用<title>Here's the Title</title>的形式,我会有很多例子可以说明,但我找不到任何像<column name="news_title">This is the title</column>

这样的引用

1 个答案:

答案 0 :(得分:1)

自从我使用xml.dom.minidom以来已经有一段时间了,但这应该有用......

columns = [c.firstChild.data for c in pmaexport.getElementsByTagName('column') if c.getAttribute('name') == 'news_title']

另外,就像列出理解一样!