JAXP DOM 操作xml

package com.lan.xml;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

//使用dom方式对xml文档crud
public class Demo3 {

	@Test
	public void create() throws SAXException, IOException, ParserConfigurationException{
		//1.创建工厂
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse("src/book.xml");
		
		//创建节点
		Element pricElement = document.createElement("二手价");
		pricElement.setTextContent("88888888元");
		
		//把创建的节点挂到第一本书上(只是改内存)
		Element book = (Element) document.getElementsByTagName("书").item(0);
		book.appendChild(pricElement);
		
		//把更新后的内存写回到xml
               	TransformerFactory tFactory = TransformerFactory.newInstance();
		Transformer tf = tFactory.newTransformer();
		tf.transform(new DOMSource(document), new StreamResult(new FileOutputStream("src/book.xml")));
	}
}



<?xml version="1.0" encoding="UTF-8" ?>
<书架>
	<书>
		<书名 name="xxxxx">lan</书名>
		<作者>lan</作者>
		<售价>100000000000000000元</售价>
	</书>
	<书>
		<书名 name="yyyyy">lll</书名>
		<作者>lll</作者>
		<售价>200000000000000000元</售价>
	</书>
</书架>


你可能感兴趣的:(JAXP DOM 操作xml)