Question

I am calling a service and I get the XML response in the below format.

How do I retrieve multiple values under a single key from this response? I want to store all the values in a List<String>

<p700:item xmlns:p700="http://abc.test.com">
    <p700:key xsi:type="xsd:string">Key1</p700:key>
    <p700:value xsi:type="xsd:string">Value1</p700:value>
    <p700:value xsi:type="xsd:string">Value2</p700:value>
    <p700:value xsi:type="xsd:string">Value3</p700:value>
    <p700:value xsi:type="xsd:string">Value14</p700:value>
</p700:item>
<p700:item xmlns:p700="http://abc.test.com">
    <p700:key xsi:type="xsd:string">Key1</p700:key>
    <p700:value xsi:type="xsd:string">Value1</p700:value>
    <p700:value xsi:type="xsd:string">Value2</p700:value>
</p700:item>
Was it helpful?

Solution

Guava has a Multimap interface and a ListMultimap implementation, which is a map of keys to multiple values contained in a list structure (as opposed to a set or sorted set). It's essentially a Map<K, Collection<V>>. You can also find examples here. As for actually parsing the XML, there are a number of questions about that here on SO, and you can start with this one.

OTHER TIPS

Create a map String <-> List<String>:

Map<String, List<String>> map = new HashMap<...>();

Use this code to add values:

List<String> values = map.get( key );
if( null == values ) {
    values = new ArrayList<String>();
    map.put( key, values );
}

values.add( "xxx" );

You can iterate over the map and add them manually to a list if you don't want to make the Map<String, List<String>> mentioned in the comments under your question.

List<String> theList = new ArrayList<String>();
String theKey = "The Key";
for(Map.Entry<String, String> entry : map.entrySet()) {
    if(entry.getKey().equals(theKey)) {
        theList.add(entry.getValue());
    }
}

This of course assumes you've already extracted the data from the XLS into a Map<String, String>. If you haven't, that's another matter entirely.

If you need a package to ingest your XLS, consider JXLS.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top