我需要知道读取以下xml代码并将结果放入对象的最佳解决方案是什么:
<accountInformation>
<customField>
<key>businessregno</key>
<value>12345</value>
</customField>
<customField>
<key>emailaddress</key>
<value>info@payat.co.za</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>
问题我尝试了一个哈希映射,但是所有元素都有相同的名称,因此我将问题填入列表中。
将它写入java对象的最佳方法是什么?
感谢您的帮助。
答案 0 :(得分:1)
我正在做类似的事情,发现w3c DOM相当不错。
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();
现在你将xml文件作为Document对象。
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);
}
现在你有了一个键/值的映射。
答案 1 :(得分:0)
如果您正在通过将属性classesToBeBound设置为pojo类来为org.springframework.oxm.jaxb.Jaxb2Marshaller处理spring create bean。