码迷,mamicode.com
首页 > 编程语言 > 详细

javaee对xml的解析练习

时间:2016-07-15 21:09:41      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:

首先是关于xml的文件,我保存的是在src目录下的

exam.xml

<?xml version="1.0" encoding="UTF-8"?>

<exam> 
  <student idcard="111" examid="222"> 
    <name>张三</name>  
    <location>沈阳</location>  
    <grade>89</grade> 
  </student>  
  <student idcard="333" examid="444"> 
    <name>李四</name>  
    <location>大连</location>  
    <grade>97</grade> 
  </student>  
  <student idcard="555" examid="666"> 
    <name name="ww">王五</name>  
    <location>武汉</location>  
    <grade>92</grade> 
  </student> 
</exam>

一、首先使用的是jaxp的dom解析实现crud

package xml_csdn_example;

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

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XML_JAXP {

	@Test
	public void test1() throws Exception {
		/*
		 * 查询所有的元素标签
		 */
		Document doc = read();
		Node item = doc.getElementsByTagName("exam").item(0);
		
		getChilder(item);  //采用的是递归函数
	}

	private void getChilder(Node item) {
		// TODO Auto-generated method stub
		System.out.println(item.getNodeName());
		
		NodeList list = item.getChildNodes();
		for(int i=0;i<list.getLength();i++){
			Node node = list.item(i);
			getChilder(node);
		}
	}
	
	
			//2、查询某一个节点
			
		@Test
		public  void test02() throws Exception{
			Document doc = read();
			Element selement = (Element) doc.getElementsByTagName("student").item(0);
			Element celement = (Element) selement.getElementsByTagName("name").item(0);
			
			
			System.out.println(selement.getAttribute("idcard"));
			System.out.println(selement.getAttribute("examid"));
				
			
			System.out.println(celement.getTextContent());
		}
	
				//3、修改某一个节点
				//3.1添加一个student
			@Test
			public  void test03() throws Exception{
				Document doc = read();
				Element element = doc.createElement("student");
				
				element.setAttribute("idcard", "777");
				element.setAttribute("examid", "888");
				
				//3.3在state中添加City和其他属性
				Element celement = doc.createElement("name");
				celement.setTextContent("毛竣锋");
				
				element.appendChild(celement);
				
				Node root = doc.getElementsByTagName("exam").item(0);
				root.appendChild(element);
				
				write();
				
			}
			
<span style="white-space:pre">			</span>//删除
			@Test
			public  void test04() throws Exception{
				Document doc = read();
				Element selement = (Element) doc.getElementsByTagName("student").item(1);
				Element name = (Element) selement.getElementsByTagName("name").item(0);
				selement.removeChild(name);
				
				write();
			}
	
	

	//读取操作
	private Document read() throws Exception {
		//查找xml,首先创建DocumentBuilderFactory实例 
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		//通过DocumentBuilderFactory实例来创建DocumentBuilder实例
		DocumentBuilder builder = factory.newDocumentBuilder();
		//通过DocumentBuilder的实例调用parse的方法来读取xml文件
		Document doc =  builder.parse("src/exam.xml");
		return doc;
	}
	
	
	//写操作
	private void write() throws Exception {
		//1、通过TransformerFactory来创建实例,调用newInstance方法
		TransformerFactory factory = TransformerFactory.newInstance();
		//2、通过TransformerFactory的实例来创建newTransformer对象
		Transformer transformer = factory.newTransformer();
		//3、用Transformer的对象的transform方法来修改xml文件
		transformer.transform(new DOMSource(), new StreamResult("src/exam.xml") );
	}
	
}

二、采用的是dom4j的工具的方法实现crud

package xml_csdn_example;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

public class XML_DOM4J {
	
	//查询,同样是可以采用递归的方法
	@Test
	public void test01() throws Exception {
		// TODO Auto-generated method stub
		Document doc = read();
		Element root = doc.getRootElement();
		List list = root.elements();
		for(int i=0;i<list.size();i++){
			System.out.println(list.get(i));
		}
		
	}
	
	//增加
	@Test
	public void test02() throws Exception {
		Document doc = read();
		Element root = doc.getRootElement();
		Element student = root.addElement("student");
		student.addAttribute("idcard", "777");
		student.addAttribute("examid", "888");
		
		student.addElement("name").addText("毛竣锋");
		student.addElement("location").addAttribute("address", "龙仙").addText("翁源");
		student.addElement("grade").addText("100");
		
		write(doc);
	}
	
	
	//修改
	@Test
	public void test03() throws Exception {
		Document doc = read();
		Element root = doc.getRootElement();
		Element element = (Element) root.elements().get(3);
		//element.addAttribute("idcard", "123");
		Element name = (Element) element.elements().get(0);
		name.setText("暴龙");
		
		write(doc);
	}
	
	
		//删除
		@Test
		public void test04() throws Exception {
			Document doc = read();
			Element root = doc.getRootElement();
			Element element = (Element) root.elements().get(3);
			//((Element)element.elements().get(1)).attribute("address").detach();
			element.detach();
			
			write(doc);
		}
	
	
	
	
	
	//采用dom4j的读取
	public Document read() throws Exception{
		SAXReader reader = new SAXReader();
		Document doc = reader.read("src/exam.xml");
		return doc;
	}
	
	//采用dom4j的修改
	private void write(Document doc) throws Exception {
		// TODO Auto-generated method stub
		XMLWriter writer = new  XMLWriter(
								new FileOutputStream("src/exam.xml"),
								OutputFormat.createPrettyPrint()
								);
		writer.write(doc);
		writer.close();
	}
}

三、 采用的是xml解析的sax解析方式

1)第一种方式是直接查询所有的标签

package xml_csdn_example;

import java.io.IOException;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.junit.Test;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class XML_SAX01 {

	//sax读取
	@Test
	public void read() throws Exception {
		// TODO Auto-generated method stub
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser saxParser = factory.newSAXParser();
		XMLReader reader = saxParser.getXMLReader();
		Mycontent m = new Mycontent();
		reader.setContentHandler(m);
		
		reader.parse("src/exam.xml");
		System.out.println(m.getPath());
	}
}



class Mycontent extends DefaultHandler{

	private String path = "";
	
	

	public String getPath() {
		return path;
	}


	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		path += "<"+qName;
		for(int i =0;i<attributes.getLength();i++){
			String value = attributes.getValue(i);
			String name = attributes.getQName(i);
			path += " " + name + "=\"" + value + "\"";
		}
		path +=">";
		
		
	}
	
	
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
			
		path +=new String(ch,start,length);
		
	}


	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {

		path +="</" + qName + ">";
		
	}

}

2)第二种方式是封装为对象,用对象来操作

package xml_example_xpath;

import java.util.ArrayList;
import java.util.List;

import javax.smartcardio.ATR;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.junit.Test;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

/*
 * 关于自主对xml的操作全部元素
 */
public class Demo5 {

	@Test
	public void Saxjiexi() throws Exception{
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser saxParser = factory.newSAXParser();
		XMLReader reader = saxParser.getXMLReader();
		
//		Mycontent handler = new Mycontent();
//		reader.setContentHandler(handler);
		
		reader.parse("./src/exam.xml");
		
		//System.out.println(handler.getPath());
		
	}
	
	@Test
	public void Saxentity() throws Exception{
		
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser saxParser = factory.newSAXParser();
		XMLReader reader = saxParser.getXMLReader();
		
		Mycontent handler = new Mycontent();
		reader.setContentHandler(handler);
		
		reader.parse("./src/exam.xml");
		
		List<Student> list = handler.getList();
		for (Student student : list) {
			System.out.println(student);
		}
	}
	
}

class Mycontent extends DefaultHandler{

	private Student student;
	private List<Student> list = new ArrayList<Student>();
	private String curtag;
	
	
	public List<Student> getList() {
		return list;
	}


	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {

		curtag=qName;
		
		if("student".equals(qName)){
			student = new Student();
			
		String idcard = attributes.getValue("idcard");
		String examid = attributes.getValue("examid");
		
		student.setExamid(examid);
		student.setIdcard(idcard);
			
		}
		
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		
		curtag = "";
		if("student".equals(qName)){
			list.add(student);
		}
		
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		String content = new String(ch, start, length);
		if("name".equals(curtag)){
			student.setName(content);
		}
		if("location".equals(curtag)){
			student.setLocation(content);
		}
		if("grade".equals(curtag)){
			student.setGrade(content);
		}
		
	}
	
}

通过这两天对xml的比较系统的学习,了解了两种解析的方法及作用,也算为xml打下了一个比较扎实的基础


javaee对xml的解析练习

标签:

原文地址:http://blog.csdn.net/css1223mjf/article/details/51915567

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!