1

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

摘要:我需要将变量分配给title其中包含的文本<column name="news_title">This is the title</column>

提取的数据库如下所示:

<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>

4

1 回答 1

1

我已经有一段时间没有使用了xml.dom.minidom,但这应该可以工作......

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

另外,例如,列表理解!

于 2012-04-18T01:10:05.787 回答