我现在有一个xml文件,我需要用java解析出来xml文件中的数据并存入sqlserver数据库中,xml文件如下:
<?xml version="1.0" encoding="utf-8"?>
<brands>
<brand>
<brandID>2</brandID>
<groupId>0</groupId>
<brandName>雅高</brandName>
<brandNameLong>雅高</brandNameLong>
<brandPinYin>YaGao</brandPinYin>
<brandFirstletter>YG</brandFirstletter>
<hotelCount>1</hotelCount>
<brandURL></brandURL>
<picURL>http://www.elongstatic.com/hotels/chain/chain192.jpg</picURL>
<lastChangetime>2011-06-10T18:06:13.933</lastChangetime>
</brand>
<brand>
<brandID>3</brandID>
<groupId>0</groupId>
<brandName>雷迪森</brandName>
<brandNameLong>雷迪森</brandNameLong>
<brandPinYin>LeiDiSen</brandPinYin>
<brandFirstletter>LDS</brandFirstletter>
<hotelCount>12</hotelCount>
<brandURL></brandURL>
<picURL>http://www.elongstatic.com/hotels/chain/chain224.jpg</picURL>
<lastChangetime>2011-06-10T18:05:49.247</lastChangetime>
</brand>
<brand>
<brandID>4</brandID>
<groupId>0</groupId>
<brandName>莱佛士</brandName>
<brandNameLong>莱佛士</brandNameLong>
<brandPinYin>LaiFoShi</brandPinYin>
<brandFirstletter>LFS</brandFirstletter>
<hotelCount>2</hotelCount>
<brandURL></brandURL>
<picURL>http://www.elongstatic.com/hotels/chain/chain231.jpg</picURL>
<lastChangetime>2011-06-10T18:06:04.090</lastChangetime>
</brand>
</brands>
------解决方案--------------------------------------------------------
首先你写个javabean,其里面属性对应到该xml节点名字,然后通过dom4j来解析Document doc = new SAXReader().read(YourClass.class.getResourceAsStream("/brands.xml"));
List elements = doc.getRootElement().elements();
List<BrandsBean> beans = new ArrayList<BrandsBean>();
for(Object obj: elements){
BrandsBean bean = new BrandsBean();
Element element = (Element)obj;
Element brandIDEle = (Element)element.selectSingleNode("brandID");
Element groupIdEle = (Element)element.selectSingleNode("brandID");
....
bean.setBrandID(brandIDEle.getText());
bean.setGroupId(groupIdEle.getText());
......
beans.add(bean);
}
然后把beans传到后台数据库方法将其中的数据进行保存,就OK了.
只是抛砖引玉哈,有些地方肯定有考虑欠缺之处!
good luck......