0

几天来,我一直在编写一个脚本,该脚本将检索 XML 文件中的标签并将其值输出到消息框。最初我打算使用 Tkinter,但我注意到它只会打印一组标签,所以我尝试使用 easygui,但我遇到了同样的问题。

我有相当多的编程经验,但我对 python 比较陌生,我在谷歌上做了几次搜索,但没有出现,所以我想我会在这里问。

这是代码中起作用的部分。

# Import our modules here.
import easygui as eg
import lxml.etree as etree

# Get our XML file here.
doc = etree.parse('file.xml')

# Grab the item tag and display the child tags name, description, and status.    
for item in doc.getiterator('item'):
    item_name = item.findtext('name')
    item_desc = item.findtext('description')
    item_status = item.findtext('status')

    # Create a variable that adds the above child tags together.
    print_xml = str((item_name + " | " + item_desc + " | " + item_status))

# Create message box to display print_xml.
    eg.msgbox(print_xml, title="XML Reader")

提前致谢!

4

1 回答 1

0

您的最后一行: eg.msgbox(...) 与您的“项目”循环中的行在同一级别缩进。因此,它为每个条目执行。

如果您希望一次显示所有条目,请在该循环内创建一个条目列表,然后将该列表组合成一个字符串。在循环之外

以下代码与您的代码相似,只是我使用了不同的 .xml 架构,因此需要对其进行一些更改。

import easygui as eg
import lxml.etree as etree

# Get our XML file here.
# From: http://msdn.microsoft.com/en-us/library/ms762271%28v=vs.85%29.aspx
doc = etree.parse('books.xml')

# Grab the item tag and display the child tags name, description, and status.
for catalog in doc.getiterator('catalog'):
    books = list()
    for item in catalog.getiterator('book'):
        item_name = item.findtext('title')
        item_desc = item.findtext('description')
        item_status = item.findtext('publish_date')

        # Create a variable that adds the above child tags together.
        books.append('{0} | {1} | {2}'.format(item_name, item_desc, item_status))

    # Create message box to display print_xml.
    eg.msgbox('\n'.join(books), title="XML Reader")

请注意创建了一个名为“books”的列表来保存您所谓的 print_xml。该列表被附加到。最后 '\n'.join(books) 用于将该列表转换为字符串,并用换行符分隔每个项目。

于 2014-12-17T05:52:12.433 回答