Python: Displaying variable with multiple xml tags inside message box

290 views Asked by At

I've been working on a script for a couple of days that will retrieve tags inside an XML file and output their values to a message box. Originally I was going to use Tkinter but I noticed that it would only print one set of tags, so I tried using easygui and I had the same problem.

I have quite a bit of experience with programming but I'm newer to python, I did several searches on google but nothing turned up so I thought I'd ask here.

Here's the part of the code that's acting up.

# 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")

Thanks in advance!

1

There are 1 answers

0
Robert Lugg On

That last line of yours: eg.msgbox(...) is indented at the same level as the lines within your 'item' loop. So, it is executed for each entry.

If you want all entries displayed at once, create a list of entries inside that loop, then combine that list into a string. outside of the loop

The following code is similar to yours except that I used a different .xml schema so needed to change it a bit.

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

Note the creation of a list called 'books' to hold what you called print_xml. That list is .appended to. Finally '\n'.join(books) is used to convert that list into a string with newlines separating each item.