(二)XML解析之Dom、Dom4j解析

Dom解析

  1. 获得Document
		//获得一个负责生产DocumentBuilder对象的工厂实例
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		//通过工厂获得一个DocumentBuilder对象,DocumentBuilder可以获得Document对象
		DocumentBuilder builder = factory.newDocumentBuilder();
		//获得document对象
		Document document = builder.parse(fileName);
  1. 将document对象写入xml文件
		//得到TransformerFactory工厂实例
		TransformerFactory tff = TransformerFactory.newInstance();
		//通过工厂得到一个转换器
		Transformer tf = tff.newTransformer();
		//设置编码
		tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		//设置格式
		//tf.setOutputProperty(OutputKeys.INDENT, "yes");
		//把一个dom模型转换成对应的xml文件
		tf.transform(new DOMSource(document), new StreamResult(fileName));

Dom4J解析

  1. 获得Document
		//获得一个SAXReader对象
		SAXReader reader = new SAXReader();
		File file = new File(filePath);
		//读取这个要解析的xml文件
		Document document = reader.read(file);
		//获得document中的根节点
		Element rootElement = document.getRootElement();
  1. 将document对象写入xml文件
		OutputFormat format = OutputFormat.createPrettyPrint();//格式美化,自动换行
		XMLWriter xw = new XMLWriter(new FileOutputStream(new File(file)),format);
		xw.write(document);
		xw.flush();
		xw.close();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值