Is there a way to add all the values of a key in the Arraylist from xml using Apache Commons Digester?

163 views Asked by At

I have an XML file with the given key-value pair mapping:

<ParentChild>
    <Parent>foo</Parent>
    <Child>bar</Child>
    <Child>bar1</Child>
    <Child>bar2</Child>
    <Child>bar3</Child>
</ParentChild>

I want to map it to the HashMap with Key Parent as String-Key and it's child as ArrayList Values as in:

HashMap(foo,(bar,bar1,bar2,bar3)) i.e. HashMap<String, ArrayList<String>>()

I am using Apache Commons Digester to get the key and values for other parameters with one key-one value relationship. But I am not sure how to map the List of Values for a single Key using digester.

I have recently started using Apache Commons Digester and any help would be great. Thank you very much.

1

There are 1 answers

2
AudioBubble On

Here is a working sample:

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.commons.digester3.Digester;
import org.xml.sax.SAXException;

public class SampleDigester {

    public void run() throws IOException, SAXException {
        Digester digester = new Digester();
        digester.addObjectCreate("ParentChildren", HashMap.class);
        digester.addCallMethod("ParentChildren/ParentChild", "put", 2);
        digester.addCallParam("ParentChildren/ParentChild/Parent", 0);
        digester.addCallParam("ParentChildren/ParentChild/Child", 1, 0);

        digester.addObjectCreate("ParentChildren/ParentChild", ArrayList.class);

        digester.addObjectCreate("ParentChildren/ParentChild/Child", StringBuffer.class);
        digester.addCallMethod("ParentChildren/ParentChild/Child", "append", 1);
        digester.addCallParam("ParentChildren/ParentChild/Child", 0);

        digester.addSetNext("ParentChildren/ParentChild/Child", "add");

        Object result = digester.parse("file:///path/to//input.xml");
        System.out.println(result);
    }

    public static void main(String[] args) {
        try {
            new SampleDigester().run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The input.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<ParentChildren>
    <ParentChild>
        <Parent>foo</Parent>
        <Child>bar</Child>
        <Child>bar1</Child>
        <Child>bar2</Child>
        <Child>bar3</Child>
    </ParentChild>
    <ParentChild>
        <Parent>fooo</Parent>
        <Child>barr</Child>
        <Child>barr1</Child>
        <Child>barr2</Child>
        <Child>barr3</Child>
    </ParentChild>
</ParentChildren>

And the output: {foo=[bar, bar1, bar2, bar3], fooo=[barr, barr1, barr2, barr3]}

I used this documentation