项目中使用XML方式去取数据插入数据代码

本文介绍如何使用DOM4J从XML文件中读取数据,并将这些数据解析后导入到数据库中。示例代码展示了如何加载XML文件、选择特定的节点以及遍历这些节点来获取属性值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、XML部分代码

<Citys>
	<City cityName="南昌市" provinceId="1"></City>
	<City cityName="赣州市" provinceId="1"></City>
	<City cityName="合肥市" provinceId="2"></City>
	<City cityName="长沙市" provinceId="3"></City>
</Citys>


2、读取数据插入数据中的java代码,使用dom4j
public void addObject(String xmlFilePath) {
		try {
			String filePath = null;
			if (xmlFilePath == null || xmlFilePath.trim().equals("")) {
				filePath = file;
			} else {
				filePath = xmlFilePath;
			}
			Document document = new SAXReader().read(Thread.currentThread()
					.getContextClassLoader().getResourceAsStream(filePath));
			importCity(document.selectNodes("//Citys/City"));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

3、解析节点插入数据库中

public void importCity(List<Element> citys) {
		for (Iterator<Element> iterator = citys.iterator(); iterator.hasNext();) {
			Element element = (Element) iterator.next();
			City city = new City();
			city.setCityName(element.attributeValue("cityName"));
			city.setpProvinceId(proDao.getProvinceById(Integer.parseInt(element.attributeValue("provinceId"))));
			super.addObject(city);
		}
	}

4、总结,这是部分代码,只能够说明使用方式,不能直接运行的代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值