JavaEE进阶(24) 删除XML文件中的数据

下面是我的Persons.xml文件内容

<?xml version="1.0" encoding="UTF-8"?>
<persons>
	<person id="0">
		<name>翠花</name>
		<age>18</age>
		<sex>女</sex>
	</person>
	<person id="1">
		<name>老王</name>
		<age>20</age>
		<sex>男</sex>
	</person>
	<person id="2">
		<name>张三</name>
		<age>19</age>
		<sex>男</sex>
	</person>
</persons>

删除数据:

/**
 * 删除XML数据
 * @author 郑清
 */
public class DeleteXMLDataDemo {

	static File file = new File("E:/eclipse-workspace/JavaEE_workspace/Day34XML/src/Persons.xml");//Persons.xml文件绝对路径
	
	public static void main(String[] args) throws Exception {
		//①获得解析器DocumentBuilder的工厂实例DocumentBuilderFactory  然后拿到DocumentBuilder对象
		DocumentBuilder newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		//②获取一个与磁盘文件关联的非空Document对象
		Document doc = newDocumentBuilder.parse(file);
		//③通过文档对象获得该文档对象的根节点
		Element root = doc.getDocumentElement();
		
		//查找指定节点
		//通过根节点获得子节点
		NodeList personList = root.getElementsByTagName("person");
		//这里获取第2个节点
		Node item = personList.item(1);
		//移出节点
		root.removeChild(item);
		
		//注意:XML文件是被加载到内存中 修改也是在内存中 ==》因此需要将内存中的数据同步到磁盘中
		/*
		 * static TransformerFactory newInstance():获取 TransformerFactory 的新实例。 
		 * abstract  Transformer newTransformer():创建执行从 Source 到 Result 的复制的新 Transformer。
		 * abstract  void transform(Source xmlSource, Result outputTarget):将 XML Source 转换为 Result。
		 */		
		Transformer transformer = TransformerFactory.newInstance().newTransformer();
		//DOMSource source = new DOMSource(doc);
		Source source = new DOMSource(doc);
		//StreamResult result = new StreamResult();
		Result result = new StreamResult(file);
		transformer.transform(source, result);//将 XML==>Source 转换为 Result
	}

}

然后我们去文件中会发现第2个节点老王的数据已经成功删除了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郑清

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值