JDK API解析XML

JDK API解析XML_第1张图片
作者:Z-AI

JDK API解析XML_第2张图片

/**
	 * @throws Exception
	 * 修改某个节点的元素内容
	 * 将第一个联系人的address的值改为重庆
	 */
	@Test
	public void test2() throws Exception {
		//获取DocumentBuilderFactory
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
		//获取解析器
		DocumentBuilder builder = builderFactory.newDocumentBuilder();
		//将内存中的XML解析为Document对象
		Document dom = builder.parse(file);
		//拿到根节点
		Element root = dom.getDocumentElement();
		//拿到第一个联系人
		Element linkman = (Element) root.getElementsByTagName("linkman").item(0);
		//拿到第一个address
		Node address = linkman.getElementsByTagName("address").item(0);
		//此时只是将内存中的数据更改了,没有做同步
		address.setTextContent("重庆");
		//同步
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		//拿到转换器
		Transformer transformer = transformerFactory.newTransformer();
		//拿到内存里面的数据
		Source domSource = new DOMSource(dom);
		//拿到磁盘上的文件
		Result result = new StreamResult(file);
		transformer.transform(domSource, result);
		
	}
	
/**
	 * @throws Exception
	 * 增加一个联系人
	 */
	@Test
	public void test3() throws Exception {
		Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
		//获取根节点
		Element root = dom.getDocumentElement();
		//创建linkman节点
		Element linkman = dom.createElement("linkman");
		linkman.setAttribute("id", "3");
		root.appendChild(linkman);
		
		//创建name
		Element name = dom.createElement("name");
		name.setTextContent("小米");
		linkman.appendChild(name);
		//创建email
		Element email = dom.createElement("email");
		email.setTextContent("[email protected]");
		linkman.appendChild(email);
		//创建address
		Element address = dom.createElement("address");
		address.setTextContent("成都高新区");
		linkman.appendChild(address);
		//创建group
		Element group = dom.createElement("group");
		group.setTextContent("小米科技有限公司");
		linkman.appendChild(group);
		
		//同步
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		Source source = new DOMSource(dom);
		Result result = new StreamResult(file);
		transformer.transform(source, result);
	}
//删除第三个联系人
	@Test
	public void test4() throws Exception {
		Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
		Element root = document.getDocumentElement();
		Node linkman = root.getElementsByTagName("linkman").item(2);
		linkman.getParentNode().removeChild(linkman);
		
		Transformer transformer = TransformerFactory.newInstance().newTransformer();
		Source source = new DOMSource(document);
		Result result = new StreamResult(file);
		transformer.transform(source, result);
	}

你可能感兴趣的:(JAVA,SE,XML解析)