java xml dom基本操作

xml文件的基本格式我们再次不在叙述。本文会建立一个学生数据库,然后实现cudr操作。。部分资源来自某java培训机构。


工程文件如下


xml格式文件名是db.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?><students>
	<student sid="001">
		<name>小明</name>
		<course>
			<java>1</java>
			<oracle>90</oracle>
			<vb>89</vb>
		</course>
	</student>
	<student sid="002">
		<name>小李</name>
		<course>
			<java>9</java>
			<oracle>70</oracle>
			<vb>8</vb>
		</course>
	</student>
	<student sid="003">
		<name>小韩</name>
		<course>
			<java>90</java>
			<oracle>70</oracle>
			<vb>85</vb>
		</course>
	</student>
	<student sid="004">
		<name>小明名</name>
		<course>
			<java>34</java>
			<oracle>50</oracle>
			<vb>58</vb>
		</course>
	</student>
	<student sid="005">
		<name>小红</name>
		<course>
			<java>29</java>
			<oracle>39</oracle>
			<vb>88</vb>
		</course>
	</student>
</students>


程序功能

几个基本准备操作

1获取Document。。。java固定要求

private static Document getDocument() throws Exception
	{
		if(!_db.exists())
		{
			System.out.println("the db file is not exits");
			return null;
		}
		
		DocumentBuilderFactory docBuilderFactorday=DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder=docBuilderFactorday.newDocumentBuilder();
		return (Document) docBuilder.parse(_db);
		
	}


2获取学生的元素链表

private static NodeList getStudents(Document _doc) throws Exception
	{
		
		if(_doc==null)
		{
			System.out.println("Document is null in view");
		}
		Element root=_doc.getDocumentElement();
		NodeList stus= root.getElementsByTagName("student");
		return stus;
	}



3定位一个学生(为了便于remove change view of操作)

private static Node locateStudents()throws Exception
	{
		
		
		NodeList stus=getStudents(_doc);
		String sidToRead;
		System.out.println("input sid to read");
		
		sidToRead=in.nextLine();
		for(int i=0;i<stus.getLength();i++)
		{
			Node stu=stus.item(i);
		
			if(!((Element)stu).getAttribute("sid").equals(sidToRead))
			{
				continue;
			}
			System.out.println("学生id"+((Element)stu).getAttribute("sid"));
			NodeList stuinfos=stu.getChildNodes();
			System.out.println("name:"+stuinfos.item(1).getTextContent());
			NodeList courses=stuinfos.item(3).getChildNodes();
			for(int j=1;j<courses.getLength();j++)
			{	
				Node course=courses.item(j);
				if(course.getNodeType()==Node.ELEMENT_NODE)
				{
					System.out.println(course.getNodeName()+"成绩:"+course.getTextContent());
				}
				
			}
			System.out.println();
			return stu;
		}
		System.out.println("the student is not 存在");
		return null;
	}



update 用于存储文件。。java固定要求

	private static void update() throws Exception
	{
		TransformerFactory tff=TransformerFactory.newInstance();
		Transformer tf=tff.newTransformer();
		tf.transform(new DOMSource(_doc), new StreamResult(new File("src/db.xml")));
		
	}



。。。

view操作

因为stus的NodeList获取的方式是直接调用getElementsByTagName(String).所以在这里没有包括因为student换行带来的TextNode元素。

private static void view() throws Exception
	{
		
		NodeList stus=getStudents(_doc);
		
		for(int i=0;i<stus.getLength();i++)
		{
			Node stu=stus.item(i);
		
			
			System.out.println("学生id"+((Element)stu).getAttribute("sid"));
			NodeList stuinfos=stu.getChildNodes();
			System.out.println("name:"+stuinfos.item(1).getTextContent());
			NodeList courses=stuinfos.item(3).getChildNodes();
			for(int j=1;j<courses.getLength();j++)
			{	
				Node course=courses.item(j);
				if(course.getNodeType()==Node.ELEMENT_NODE)
				{
					System.out.println(course.getNodeName()+"成绩:"+course.getTextContent());
				}
				
			}
			System.out.println();
		}
		
	}


view of

	private static void view_of() throws Exception
	{
		locateStudents();
	}
	

add 操作非常麻烦,因为这里你要考虑因为换行所带来的TextNode元素。这样才能使新加入的Node和原来从文件中读入的Node一样的进行view或者view of。可能有更好的方法进行编程,在此我没有探究如何更加方便的编程,只是强行的childrenNode里面加入TextNode,来模拟XML文件中的换行。注释处是调试代码。

private static void add()throws Exception
	{
	
		NodeList stus=getStudents(_doc);
		Element lastStudent=(Element) stus.item(stus.getLength()-1);
		
		Element newStu=_doc.createElement("student");
		newStu.setAttribute("sid", String.format("%03d",Integer.parseInt(lastStudent.getAttribute("sid"))+1));
		newStu.appendChild(_doc.createTextNode("\n"));
		
		
		
		
		
		Element newName=_doc.createElement("name");
		System.out.println("intput name");
		String inputName=in.nextLine();
		newName.setTextContent(inputName);
		newStu.appendChild(newName);
		newStu.appendChild(_doc.createTextNode("\n"));
		
		

				
		Element newCourse=_doc.createElement("course");
		newCourse.appendChild(_doc.createTextNode("\n"));
		Element newJava=_doc.createElement("java");
		System.out.println("input java mark");
		String javaMark=in.nextLine();
		newJava.setTextContent(javaMark);
		newCourse.appendChild(newJava);
		newCourse.appendChild(_doc.createTextNode("\n"));
		Element newOricle=_doc.createElement("oricle");
		System.out.println("input oricle mark");
		String oricleMark=in.nextLine();
		newOricle.setTextContent(oricleMark);
		newCourse.appendChild(newOricle);
		newCourse.appendChild(_doc.createTextNode("\n"));
		Element newVb=_doc.createElement("vb");
		System.out.println("input oricle mark");
		String vbMark=in.nextLine();
		newVb.setTextContent(vbMark);
		newCourse.appendChild(newVb);
		newCourse.appendChild(_doc.createTextNode("\n"));
		

		newStu.appendChild(newCourse);
		newStu.appendChild(_doc.createTextNode("\n"));
//		System.out.println(newStu.getTextContent());
		
//		NodeList chileds=newCourse.getChildNodes();
//		for(int i=0;i<chileds.getLength();i++)
//		{
//			Node n=chileds.item(i);
//			System.out.println(n.getNodeName());
//		}
		lastStudent.getParentNode().appendChild(newStu);
	}


change

private static void change() throws Exception
	{
		Element stu=(Element) locateStudents();
		System.out.println("input the course to edit");
		String courseToEdit=in.nextLine();
		NodeList courses=stu.getElementsByTagName("course").item(0).getChildNodes();
		for(int i=0;i<courses.getLength();i++)
		{
			Node course=courses.item(i);
			System.out.println(course.getNodeName());
			if(!course.getNodeName().equals(courseToEdit))
			{
				continue;
			}
			System.out.println("input mark");
			String courseMark=in.nextLine();
			course.setTextContent(courseMark);
			
			return;
		}
		System.out.println("not find course");
		return;
		
	}


remove和save

	private static void remove() throws Exception
	{
		Node decStu=locateStudents();
		decStu.getParentNode().removeChild(decStu);
		
	}
	
	private static void save() throws Exception
	{
		update();
	}


最后附上这个程序所有的代码。

package day2;

import java.io.File;
import java.util.Scanner;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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 Main {
	
	private static File _db;
	private static Document _doc;
	private static Scanner in;
	
	public static void main(String args[])throws Exception
	{
		_db=new File("src/db.xml");
		_doc=getDocument();
		String option;
		in=new Scanner(System.in);

		boolean isContinue=true;
		while(isContinue)
		{
			System.out.print("view:查看所有学生成绩\n"+
					"view of:按照学生id查询学生成绩\n"+
					"add: 添加一个学生\n"+
					"change: 按照id修改一个学生\n"+
					"remove:按照id去删除一个学生\n"+
					"save: 保存学生信息\n"+
					"exit: 退出系统\n"
					);
			option=in.nextLine();
			
			switch(option)
			{
			case"view":
				view();
				break;
			case"view of":
				view_of();
				break;
			case"add":
				add();
				break;
			case"change":
				change();
				break;
			case"remove":
				remove();
				break;
			case"save":
				save();
				break;
			case"exit":
				isContinue=false;
				break;
			default:
				System.out.println("you input have something wrong,go it again");
				break;
			}
			
		}
		System.out.println("bye");
	}
	
	
	


	
	private static Document getDocument() throws Exception
	{
		if(!_db.exists())
		{
			System.out.println("the db file is not exits");
			return null;
		}
		
		DocumentBuilderFactory docBuilderFactorday=DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder=docBuilderFactorday.newDocumentBuilder();
		return (Document) docBuilder.parse(_db);
		
	}




	private static NodeList getStudents(Document _doc) throws Exception
	{
		
		if(_doc==null)
		{
			System.out.println("Document is null in view");
		}
		Element root=_doc.getDocumentElement();
		NodeList stus= root.getElementsByTagName("student");
		return stus;
	}
	
	
	
	private static Node locateStudents()throws Exception
	{
		
		
		NodeList stus=getStudents(_doc);
		String sidToRead;
		System.out.println("input sid to read");
		
		sidToRead=in.nextLine();
		for(int i=0;i<stus.getLength();i++)
		{
			Node stu=stus.item(i);
		
			if(!((Element)stu).getAttribute("sid").equals(sidToRead))
			{
				continue;
			}
			System.out.println("学生id"+((Element)stu).getAttribute("sid"));
			NodeList stuinfos=stu.getChildNodes();
			System.out.println("name:"+stuinfos.item(1).getTextContent());
			NodeList courses=stuinfos.item(3).getChildNodes();
			for(int j=1;j<courses.getLength();j++)
			{	
				Node course=courses.item(j);
				if(course.getNodeType()==Node.ELEMENT_NODE)
				{
					System.out.println(course.getNodeName()+"成绩:"+course.getTextContent());
				}
				
			}
			System.out.println();
			return stu;
		}
		System.out.println("the student is not 存在");
		return null;
	}
	
	private static void update() throws Exception
	{
		TransformerFactory tff=TransformerFactory.newInstance();
		Transformer tf=tff.newTransformer();
		tf.transform(new DOMSource(_doc), new StreamResult(new File("src/db.xml")));
		
	}
	private static void view() throws Exception
	{
		
		NodeList stus=getStudents(_doc);
		
		for(int i=0;i<stus.getLength();i++)
		{
			Node stu=stus.item(i);
		
			
			System.out.println("学生id"+((Element)stu).getAttribute("sid"));
			NodeList stuinfos=stu.getChildNodes();
			System.out.println("name:"+stuinfos.item(1).getTextContent());
			NodeList courses=stuinfos.item(3).getChildNodes();
			for(int j=1;j<courses.getLength();j++)
			{	
				Node course=courses.item(j);
				if(course.getNodeType()==Node.ELEMENT_NODE)
				{
					System.out.println(course.getNodeName()+"成绩:"+course.getTextContent());
				}
				
			}
			System.out.println();
		}
		System.out.println(stus.getLength());
	}
	
	
	
	private static void view_of() throws Exception
	{
		locateStudents();
	}
	
	private static void add()throws Exception
	{
	
		NodeList stus=getStudents(_doc);
		Element lastStudent=(Element) stus.item(stus.getLength()-1);
		
		Element newStu=_doc.createElement("student");
		newStu.setAttribute("sid", String.format("%03d",Integer.parseInt(lastStudent.getAttribute("sid"))+1));
		newStu.appendChild(_doc.createTextNode("\n"));
		
		
		
		
		
		Element newName=_doc.createElement("name");
		System.out.println("intput name");
		String inputName=in.nextLine();
		newName.setTextContent(inputName);
		newStu.appendChild(newName);
		newStu.appendChild(_doc.createTextNode("\n"));
		
		

				
		Element newCourse=_doc.createElement("course");
		newCourse.appendChild(_doc.createTextNode("\n"));
		Element newJava=_doc.createElement("java");
		System.out.println("input java mark");
		String javaMark=in.nextLine();
		newJava.setTextContent(javaMark);
		newCourse.appendChild(newJava);
		newCourse.appendChild(_doc.createTextNode("\n"));
		Element newOricle=_doc.createElement("oricle");
		System.out.println("input oricle mark");
		String oricleMark=in.nextLine();
		newOricle.setTextContent(oricleMark);
		newCourse.appendChild(newOricle);
		newCourse.appendChild(_doc.createTextNode("\n"));
		Element newVb=_doc.createElement("vb");
		System.out.println("input oricle mark");
		String vbMark=in.nextLine();
		newVb.setTextContent(vbMark);
		newCourse.appendChild(newVb);
		newCourse.appendChild(_doc.createTextNode("\n"));
		

		newStu.appendChild(newCourse);
		newStu.appendChild(_doc.createTextNode("\n"));
//		System.out.println(newStu.getTextContent());
		
//		NodeList chileds=newCourse.getChildNodes();
//		for(int i=0;i<chileds.getLength();i++)
//		{
//			Node n=chileds.item(i);
//			System.out.println(n.getNodeName());
//		}
		lastStudent.getParentNode().appendChild(newStu);
	}
	

	
	private static void change() throws Exception
	{
		Element stu=(Element) locateStudents();
		System.out.println("input the course to edit");
		String courseToEdit=in.nextLine();
		NodeList courses=stu.getElementsByTagName("course").item(0).getChildNodes();
		for(int i=0;i<courses.getLength();i++)
		{
			Node course=courses.item(i);
			System.out.println(course.getNodeName());
			if(!course.getNodeName().equals(courseToEdit))
			{
				continue;
			}
			System.out.println("input mark");
			String courseMark=in.nextLine();
			course.setTextContent(courseMark);
			
			return;
		}
		System.out.println("not find course");
		return;
		
	}
	
	private static void remove() throws Exception
	{
		Node decStu=locateStudents();
		decStu.getParentNode().removeChild(decStu);
		
	}
	
	private static void save() throws Exception
	{
		update();
	}
	
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值