Re: Parse MULTIPLE XML files in a directory

Stefan Behnel <[email protected]>
Newsgroups gmane.comp.python.xml
Message-ID <[email protected]>
Hi,

first thing: don't use expat directly. Use (c)ElementTree's iterparse. It's in
Python 2.5, but is also available as an external package for older Python
versions. There's also lxml (which is mostly compatible to ElementTree), in
case you ever need features like XPath, XSLT or whatever.


amitesh kumar wrote:
> Please review the following code and help me.
> 
> Here I'm trying to :
> 1. Read each XML file in a folder.
> 2. Parse file.
> 3. Store some of the tags values as key-value pair in a map
> 4. Similarly maintain another collection that'll store one list per file.
> ------------------------------------------------------------------------
>
> ordtags = set()
> shptags = set()
> omptags = set()
> 
> ordtags.add('orrfnbr')
> ordtags.add('afidlog')
[...]

Better:

    ordtags = set(['offfnbr', 'afidlog', ...])

    from xml.etree.cElementTree import iterparse

    for onefile in allfiles:
        for event, element in iterparse(onefile):
            if element.tag in ordtags:
                 # do something like
                 values[element.tag] = element.text
            elif element.tag in shptags:
                 # do something else
            else:
                 # don't do anything?
            element.clear()

Stefan
_______________________________________________
XML-SIG maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/xml-sig
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.