Java之删除XML文件中的数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38225558/article/details/82745196

下面是我的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个节点老王的数据已经成功删除了

猜你喜欢

转载自blog.csdn.net/qq_38225558/article/details/82745196