2

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>
Brian
  • 17,079
  • 6
  • 43
  • 66
rvelagaleti
  • 51
  • 2
  • 5
  • 3
    Create a `Map>`. – KV Prajapati Oct 08 '12 at 15:16
  • Was that your query more about parsing such a XML response? If you have webservice (codefirst) you would have had defined request/response data structure as pojos.I guess you should be getting list of item objects, but parsing could be bit trickier as it has attributes. – Satheesh Cheveri Oct 08 '12 at 17:39

3 Answers3

1

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" );
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
0

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.

asteri
  • 11,402
  • 13
  • 60
  • 84
0

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.

Community
  • 1
  • 1
Brian
  • 17,079
  • 6
  • 43
  • 66