commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Craig McClanahan <craig...@gmail.com>
Subject Re: [Digester] basic usage problem. Help me understand the stack.
Date Tue, 27 Jul 2004 01:54:34 GMT
On Tue, 27 Jul 2004 13:24:00 +1200, Simon Kitching
<simon@ecnetwork.co.nz> wrote:
> On Tue, 2004-07-27 at 13:17, Rich Coco wrote:
> >
> > Suppose you need to parse the xml and return, say, a hashtable
> > containing the associated java objects.
> >

In other words you want to flatten the hierarchy?  That doesn't seem
like something you *have* to do while parsing (if you do, then you
might need some custom Digester rules -- doable, but more work). 
Instead, assuming the Part data structure that I identified in my
earlier response, you can create a flattened Map after the parse
completes, like this:

    Part dummy = ... the dummy part from earlier ...
    Map flattened = new HashMap();
    Iterator parts = dummy.getParts().iterator();
    while (parts.hasNext()) {
        flatten(flattened, (Part) parts.next());
    }


    // Private method that recursively flattens a part structure
    private void flatten(Map map, Part part) {
        // Add this part to the map
        map.put(new Integer(part.getId()), part);
        // Add the sub-parts of this part to the map recursively
        Iterator parts = part.getParts();
        while (parts.hasNext()) {
            flatten(map, (Part) parts.next());
        }
    }

With an extra "if" statement, you can do things like check for
duplicate part ids, if that is needed.

The extra loop in the main body of the code is based on the assumption
that the dummy top-level Part isn't a "real" Part ... it's just a
collector.  If it is real (in other words, if the entire BOM you are
parsing is to construct a single assembly), the main line code is even
simpler:

    Part dummy = ... the dummy part from earlier ...
    Map flattened = new HashMap();
    flatten(flattened, dummy);

Craig

---------------------------------------------------------------------
To unsubscribe, e-mail: commons-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-user-help@jakarta.apache.org


Mime
View raw message