java--对XML文件操作(增删改查)

xml文件source.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<scores>
	<score>
		<id>2</id>
		<name>李佳</name>
		<course>sql</course>
		<grade>99</grade>
	</score>	
    <score>
        <id>3</id>
        <name>李明</name>
        <course>数据结构</course>
        <grade>90</grade>
    </score>
</scores>

新增节点

步骤:
1.创建节点
2.找到需要插入的父节点
3.插入节点
4.保存文件

package com.zhiyou.xmlDemo;

import java.io.FileOutputStream;

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.TransformerFactory;
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.Node;
import org.w3c.dom.NodeList;

public class TestAdd {
	public static void main(String[] args) throws Exception {
		addNode();
	}
	
	public static void addNode() throws Exception {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		//parse把xml文件转换成dom树
		Document doc =db.parse("src/xmlDemo/source.xml");
		
		//获取节点
		//获取根节点的集合
		NodeList childNodes = doc.getChildNodes();
		
		//得到根节点
		Node scores = childNodes.item(0);
		
		//创建score节点
		Element score = doc.createElement("score");
		
		//创建id节点并赋值
		Element id = doc.createElement("id");
		id.setTextContent("3");
		
		//创建name节点并赋值
		Element name = doc.createElement("name");
		name.setTextContent("李明");
		
		//创建course节点并赋值
		Element course = doc.createElement("course");
		course.setTextContent("数据结构");
		
		//创建grade节点并赋值
		Element grade= doc.createElement("grade");
		grade.setTextContent("80");
		
		scores.appendChild(score);
		score.appendChild(id);
		score.appendChild(name);
		score.appendChild(course);
		score.appendChild(grade);
		
		//把最新的数据保存到文件
		//保存xml文件
		TransformerFactory tff = TransformerFactory.newInstance();
		Transformer t = tff.newTransformer();
		DOMSource domSource = new DOMSource(doc);
		//设置编码类型
		t.setOutputProperty(OutputKeys.ENCODING, "utf-8");
		
		StreamResult result = new StreamResult(new FileOutputStream("src/xmlDemo/source.xml"));
		
		//把DOM树转换为XML文件
		t.transform(domSource, result);
		
		
		
		
		
	}
}

删除节点

package xmlDemo;

import java.io.FileOutputStream;

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

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class TestDelete {
	public static void main(String[] args) throws Exception {
		String name = "王同";
		deleteNode(name);
	}
	
	public static void deleteNode(String name) throws Exception{
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		//parse把xml文件转换成dom树
		Document doc =db.parse("src/xmlDemo/source.xml");
		
		//获取节点
		//得到根节点的集合
		NodeList childNodes = doc.getChildNodes();
		
		
		//得到根节点
		Node root = childNodes.item(0);
		
		//怎么继续遍历
		//得到score节点
		NodeList scores = root.getChildNodes();
		
		
		for(int i = 0;i<scores.getLength();i++) {
			//得到一个score
			Node score = scores.item(i);
			//得到这个score的所有子节点
			NodeList items = score.getChildNodes();
			//遍历这个score所有的节点
			for(int j=0;j<items.getLength();j++) {
				//得到一个节点
				Node item = items.item(j);
				if("id".equals(item.getNodeName())) {
					//获取节点内的文本值
					System.out.println("id编号"+item.getTextContent());
					//getNodeType()获取节点类型  
					//
//					System.out.println("id编号"+item.getNodeType());
				}
				if("name".equals(item.getNodeName())) {
					if(name.equals(item.getTextContent())) {
						//item 指name节点
						//item.getParentNode() 指score节点
						//item.getParentNode().getParentNode() 指scores节点
						//removeChild(score)  删除与指定name一致的学生的信息
						item.getParentNode().getParentNode().removeChild(score);
					}
				}
				}
			}
	
		//把最新的数据保存到文件
		//保存xml文件
		TransformerFactory tff = TransformerFactory.newInstance();
		Transformer t = tff.newTransformer();
		DOMSource domSource = new DOMSource(doc);
		//设置编码类型
		t.setOutputProperty(OutputKeys.ENCODING, "utf-8");
		
		StreamResult result = new StreamResult(new FileOutputStream("src/xmlDemo/source.xml"));
		
		//把DOM树转换为XML文件
		t.transform(domSource, result);
	}
	
	
	
	
	}

修改节点的文本的值

package xmlDemo;

import java.io.FileOutputStream;
import java.io.IOException;

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

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

public class TestUpdate {
	public static void main(String[] args) throws Exception {
		updateNode();
	}
	
	public static void updateNode() throws Exception {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		//parse把xml文件转换成dom树
		Document doc =db.parse("src/xmlDemo/source.xml");
		
		//获取节点
		//获取根节点的集合
		NodeList childNodes = doc.getChildNodes();
		
		//得到根节点scores
		Node root = childNodes.item(0);	
		//怎么继续遍历
		//得到scores节点的子代节点集合
		NodeList scores = root.getChildNodes();
	
		for(int i = 0;i<scores.getLength();i++) {
			//得到一个score
			Node score = scores.item(i);
			//得到这个score的所有子节点
			NodeList items = score.getChildNodes();
			//遍历这个score所有的节点
			for(int j=0;j<items.getLength();j++) {
				//得到一个节点
				Node item = items.item(j);
				
				if("grade".equals(item.getNodeName())) {
					item.setTextContent("100");
				}
			}
		}
		//把最新的数据保存到文件
		//保存xml文件
		TransformerFactory tff = TransformerFactory.newInstance();
		Transformer t = tff.newTransformer();
		DOMSource domSource = new DOMSource(doc);
		//设置编码类型
		t.setOutputProperty(OutputKeys.ENCODING, "utf-8");
		
		StreamResult result = new StreamResult(new FileOutputStream("src/xmlDemo/source.xml"));
		
		//把DOM树转换为XML文件
		t.transform(domSource, result);
	}
}

根据标签属性修改
java--对XML文件操作(增删改查)_第1张图片

查看节点文本的值

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.*;


public class TestRead {
	public static void main(String[] args) throws Exception {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		//parse把xml文件转换成dom树
		Document doc =db.parse("src/xmlDemo/source.xml");
		
		//获取节点
		//获取根节点的集合
		NodeList childNodes = doc.getChildNodes();
		
		
		//得到根节点scores
		Node root = childNodes.item(0);
		
		//怎么继续遍历
		//得到scores节点的子代节点集合
		NodeList scores = root.getChildNodes();
		System.out.println(scores.getLength());
		
		for(int i = 0;i<scores.getLength();i++) {
			//scores.item(i)得到一个scores子节点或空白节点
			if(scores.item(i).getNodeType()==3) {
				continue;
			}
			Node score = scores.item(i);
			//得到这个score的所有子节点
			NodeList items = score.getChildNodes();
			//遍历这个score所有的节点
			for(int j=0;j<items.getLength();j++) {
				//items.item(i)得到一个score子节点或空白节点
				if(items.item(j).getNodeType()==3) {
					continue;
				}
				//得到一个节点
				Node item = items.item(j);
				if("id".equals(item.getNodeName())) {
					//获取节点内的文本值
					System.out.println("id编号"+item.getTextContent());
					//getNodeType()获取节点类型  
					// 1(元素节点)  2(属性节点)  3(空白节点)
					//System.out.println("元素节点:"+item.getNodeType());
				}
				if("name".equals(item.getNodeName())) {
					System.out.println("姓名"+item.getTextContent());
				}
				if("course".equals(item.getNodeName())) {
					System.out.println("课程"+item.getTextContent());
				}
				if("grade".equals(item.getNodeName())) {
					System.out.println("成绩"+item.getTextContent());
				}
			}
		}
	}
}

你可能感兴趣的:(XML)