Use JAXB
to read from xml
and save it in a custom object.
User class of the object:
import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement(name = "Details") @XmlType(propOrder = { "detailA", "detailB" }) public class Details { private List<String> detailA; private List<String> detailB; public void setDetailA(List<String> detailA) { this.detailA = detailA; } @XmlElementWrapper(name = "detail-a") @XmlElement(name = "detail") public List<String> getDetailA() { return detailA; } public void setDetailB(List<String> detailB) { this.detailB = detailB; } @XmlElementWrapper(name = "detail-b") @XmlElement(name = "detail") public List<String> getDetailB() { return detailB; } }
Extract the data from your xml into the object, then add the contents to the map as desired:
public static void main(String[] args) throws JAXBException, FileNotFoundException { System.out.println("Output from our XML File: "); JAXBContext context = JAXBContext.newInstance(Details.class); Unmarshaller um = context.createUnmarshaller(); Details details = (Details)um.unmarshal(new FileReader("details.xml")); List<String> detailA = details.getDetailA(); List<String> detailB = details.getDetailB(); Map<String, String[]> map = new HashMap<String, String[]>(); map.put("detail-a", detailA.toArray(new String[detailA.size()])); map.put("detail-b", detailB.toArray(new String[detailB.size()])); for (Map.Entry<String, String[]> entry : map.entrySet()) {
The output will be:
Output from our XML File:
Key "detail-a" value = {"attribute 1 of detail a", "attribute 2 of detail a", "attribute 3 of detail a"}
Key "detail-b" value = {"attribute 1 of detail b", "attribute 2 of detail b"}
As a side note: this will only work for the xml that you provided as input in your question, if you need to add more details, like detail-c
, etc., you should also define them in your custom object.
XML Used:
<?xml version="1.0" encoding="utf-8"?> <Details> <detail-a> <detail>attribute 1 of detail a</detail> <detail>attribute 2 of detail a</detail> <detail>attribute 3 of detail a</detail> </detail-a> <detail-b> <detail>attribute 1 of detail b</detail> <detail>attribute 2 of detail b</detail> </detail-b> </Details>
source share