JAVA中使用DOM操作XML

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DOMReadXml {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse("C:\\scores.xml");
			//展示XML
			showMXL(doc);	
			//addXML(doc);
			//Motify(doc);
			saveXML(doc);
			delete(doc);
			System.out.println("修改后的代码!!!!!");
			showMXL(doc);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//读取XML文档并显示
	public static void showMXL(Document doc) {
		NodeList studentList = doc.getElementsByTagName("student");
		for(int i=0;i<studentList.getLength();i++){
			if(!(studentList.item(i) instanceof Element)){
				continue;
			}
			//获取元素节点
			Element studentElement = (Element)studentList.item(i);
			//获取属性
			String id = studentElement.getAttribute("id");
			//获取元素文本
			String name = ((Element)studentElement.getElementsByTagName("name").item(0)).getFirstChild().getNodeValue();
			String course = ((Element)studentElement.getElementsByTagName("course").item(0)).getFirstChild().getNodeValue();
			String score = ((Element)studentElement.getElementsByTagName("score").item(0)).getFirstChild().getNodeValue();
			System.out.println(id+"\t"+name+"\t"+course+"\t"+score);
		}
	}
	
	//添加XML并保存
	public static void addXML(Document doc){
		Element nameElement = doc.createElement("name");
		Element courseElement = doc.createElement("course");
		Element scoreElement = doc.createElement("score");
		
		nameElement.setTextContent("历史");
		courseElement.setTextContent("C#");
		scoreElement.setTextContent("100");
		
		Element student = doc.createElement("student");
		student.setAttribute("id", "3");
		student.appendChild(nameElement);
		student.appendChild(courseElement);
		student.appendChild(scoreElement);
		
		doc.getChildNodes().item(0).appendChild(student);
		//保存XML
		saveXML(doc);
		
	}

	//保存XML
	private static void saveXML(Document doc)
			throws TransformerFactoryConfigurationError {
		TransformerFactory dff = TransformerFactory.newInstance();
		try {
			Transformer tf = dff.newTransformer();
			DOMSource ds = new DOMSource(doc);
			tf.setOutputProperty(OutputKeys.ENCODING,"GB2312");
			StreamResult result = new StreamResult("C:\\scores.xml");
			tf.transform(ds, result);
			
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//修改XML文档
	private static void Motify(Document doc){
		//找到节点列表
		NodeList studentList = doc.getElementsByTagName("student");
		for(int i=0;i<studentList.getLength();i++){
			if(!(studentList.item(i) instanceof Element)){
				continue;
			}
			Element studentElement = (Element)studentList.item(i);
			//获取元素的id属性
			String id = studentElement.getAttribute("id");
			if(id.equals("3")){
				//设置属性
				studentElement.setAttribute("id", "4");
				//设置元素的另一个子节点
				studentElement.getElementsByTagName("name").item(0).setTextContent("张三");
				break;
			}
		}
	}
	//实现XML节点的删除
	private static void delete(Document doc){
		
		NodeList studentList = doc.getElementsByTagName("student");
		for(int i=0;i<studentList.getLength();i++){
			if(!(studentList.item(i) instanceof Element)){
				continue;
			}
			Element studentElement = (Element)studentList.item(i);
			String id = studentElement.getAttribute("id");
			if(id.equals("3")){
				//找到需要删除节点的父节点,然后移除需要删除的节点
				studentElement.getParentNode().removeChild(studentElement);
				break;
			}
		}
	}

}


所对应的XML文件为:

<?xml version="1.0" encoding="gb2312" ?>
<scores>
	<student id="1">
		<name>王同</name>
		<course>java</course>
		<score>89</score>
	</student>
	<student id="2">
		<name>李佳</name>
		<course>sql</course>
		<score>88</score>
	</student>
</scores>


你可能感兴趣的:(java,xml,dom)