Reputation: 23
I need to know what the best solution would be to read the following xml code and place the result into objects:
<accountInformation>
<customField>
<key>businessregno</key>
<value>12345</value>
</customField>
<customField>
<key>emailaddress</key>
<value>[email protected]</value>
</customField>
<customField>
<key>idnumber</key>
<value>8601095195084</value>
</customField>
<customField>
<key>initial</key>
<value>J</value>
</customField>
<customField>
<key>lastname</key>
<value>Boshoff</value>
</customField>
<customField>
<key>licensetype</key>
<value>07</value>
</customField>
<customField>
<key>licensetypedescription</key>
<value>Normal</value>
</customField>
<customField>
<key>loaduserid</key>
<value>12345</value>
</customField>
<customField>
<key>passportno</key>
<value>1234512345</value>
</customField>
<customField>
<key>title</key>
<value>Mr</value>
</customField>
<customField>
<key>validationrefno</key>
<value>0</value>
</customField>
<customField>
<key>accountnumber</key>
<value>608806709</value>
</customField>
<customField>
<key>balance</key>
<value>500</value>
</customField>
<customField>
<key>contactno</key>
<value>0846769478</value>
</customField>
<customField>
<key>landlinecontactno</key>
<value>0218865557</value>
</customField>
<customField>
<key>physicaladdress</key>
<value>SUITE 4,OU KOLLEGE GEBOU,STELLIES,WESTERN PROVINCE,5600,35,CHURCH STREET,</value>
</customField>
<customField>
<key>validity</key>
<value>true</value>
</customField>
</accountInformation>
The problem I have tried a hash map, but all the elements have the same name so I have a issue populating it into a list.
What would be the best way for me to write it into java objects?
Thank you for the help.
Upvotes: 0
Views: 133
Reputation: 1032
I'm doing something similar and found the w3c DOM is pretty decent.
File xmlFile = new File(path);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature(
"http://apache.org/xml/features/nonvalidating/load-external-dtd",
false);
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(xmlFile); //or parse the String
document.getDocumentElement().normalize();
So now you have the xml file as a Document object.
Map<String, String> map = new HashMap<String, String>();
NodeList nodelist = document.getElementsByTagName("customField")
for (int i=0; i<nodelist.getLength(); i++) {
Element element = (Element) nodelist.item(i);
String key = element.getAttributes("key");
String value = element.getAttributes("value");
map.put(key,value);
}
And now you have a map of key/values.
Upvotes: 1
Reputation: 1
If you are working on spring create bean for org.springframework.oxm.jaxb.Jaxb2Marshaller by setting property classesToBeBound to pojo class.
Upvotes: 0