欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java解析XML的方法

程序员文章站 2022-05-22 16:39:09
...
XML可扩展标记语言,标准通用标记语言的子集,是一种用于标记电子文件使其具有结构性的标记语言。
在电子计算机中,标记指计算机所能理解的信息符号,通过此种标记,计算机之间可以处理包含各种的信息比如文章等。它可以用来标记数据、定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言。 它非常适合万维网传输,提供统一的方法来描述和交换独立于应用程序或供应商的结构化数据。是Internet环境中跨平台的、依赖于内容的技术,也是当今处理分布式结构信息的有效工具。早在1998年,W3C就发布了XML1.0规范,使用它来简化Internet的文档信息传输。(以上台词在娘度那ლ(╹◡╹ლ))
        XML在不同的语言里解析方式都是一样的,只不过实现的语法不同而已。基本的解析方式有两种,一种叫SAX,另一种叫DOM。SAX是基于事件流的解析,DOM是基于XML文档树结构的解析。
在java中解析xml的方法有DOMSAXDOM4JJDOM……
EINS:DOM方式↓(优点:整个文档树在内存中,便于操作;支持删除、修改、重新排列等多种功能;缺点:将整个文档调入内存(包括无用的节点),浪费时间和空间;使用场合:一旦解析了文档还需多次访问这些数据;硬件资源充足(内存、CPU)。 
XmlDOMImpl.java
package com.xml; 

import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.PrintWriter; 
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.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; 
import org.xml.sax.SAXException; 
/** 
 * 
 * @author 夜月
 * DOM生成与解析XML文档 
 */ 
public class XmlDOM{ 
	private Document document; 
	private String fileName; 
	
	public XmlDOMImpl() {
		init();
	}
	
	public void init() { 
		try { 
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
			DocumentBuilder builder = factory.newDocumentBuilder(); 
			this.document = builder.newDocument(); 
		} catch (ParserConfigurationException e) { 
			System.out.println(e.getMessage()); 
		} 
	}
	
	public void createXml(String fileName) { 
		Element root = this.document.createElement("ELs"); 
		this.document.appendChild(root);
		
		Element El = this.document.createElement("El"); 
		Element name = this.document.createElement("name"); 
		name.appendChild(this.document.createTextNode("夜月")); 
		El.appendChild(name);
		
		Element sex = this.document.createElement("sex"); 
		sex.appendChild(this.document.createTextNode("M")); 
		El.appendChild(sex);
		
		Element age = this.document.createElement("age"); 
		age.appendChild(this.document.createTextNode("23")); 
		El.appendChild(age);
		
		root.appendChild(El); 
		TransformerFactory tf = TransformerFactory.newInstance();
		
		try {
			Transformer transformer = tf.newTransformer();
			DOMSource source = new DOMSource(document);
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); 
			transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
			PrintWriter pw = new PrintWriter(new FileOutputStream(fileName)); 
			StreamResult result = new StreamResult(pw); 
			transformer.transform(source, result); 
			System.out.println("生成XML文件成功!"); 
		} catch (TransformerConfigurationException e) { 
			System.out.println(e.getMessage()); 
		} catch (IllegalArgumentException e) { 
			System.out.println(e.getMessage()); 
		} catch (FileNotFoundException e) { 
			System.out.println(e.getMessage()); 
		} catch (TransformerException e) { 
			System.out.println(e.getMessage()); 
		} 
	} 
	
	public void parseXml(String fileName) { 
		try { 
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
			DocumentBuilder db = dbf.newDocumentBuilder(); 
			Document document = db.parse(fileName);
			NodeList root = document.getChildNodes(); 
			for (int i = 0; i < root.getLength(); i++) { 
				Node EL = root.item(i); 
				NodeList ELInfo = EL.getChildNodes(); 
				for (int j = 0; j < ELInfo.getLength(); j++) {
					Node node = ELInfo.item(j);
					
					NodeList ELMeta = node.getChildNodes(); 
					for (int k = 0; k < ELMeta.getLength(); k++) {
						System.out.println(ELMeta.item(k).getNodeName() + ":" + ELMeta.item(k).getTextContent()); 
					} 
				} 
			} 
			System.out.println("解析完毕"); 
		} catch (FileNotFoundException e) { 
			System.out.println(e.getMessage()); 
		} catch (ParserConfigurationException e) { 
			System.out.println(e.getMessage()); 
		} catch (SAXException e) { 
			System.out.println(e.getMessage()); 
		} catch (IOException e) { 
			System.out.println(e.getMessage()); 
		} 
	} 
	
	
} 
 
ZWEI:SAX方式↓(优点:不用事先调入整个文档,占用资源少;SAX解析器代码比DOM解析器代码小,适于Applet,下载。缺点:不是持久的;事件过后,若没保存数据,那么数据就丢了;无状态性;从事件中只能得到文本,但不知该文本属于哪个元素;使用场合:Applet;只需XML文档的少量内容,很少回头访问;机器内存少;
XmlSAX.java
package com.xml; 

import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
import javax.xml.parsers.ParserConfigurationException; 
import javax.xml.parsers.SAXParser; 
import javax.xml.parsers.SAXParserFactory; 
import org.xml.sax.Attributes; 
import org.xml.sax.SAXException; 
import org.xml.sax.helpers.DefaultHandler; 
/** 
 * 
 * @author 夜月 
 * SAX文档解析 
 */ 
public class XmlSAX{ 
	
	public void createXml(String fileName) { 
		System.out.println("<<" + fileName + ">>"); 
	}
	
	public void parseXml(String fileName) { 
		SAXParserFactory saxfac = SAXParserFactory.newInstance(); 
		try { 
			SAXParser saxparser = saxfac.newSAXParser(); 
			InputStream is = new FileInputStream(fileName); 
			saxparser.parse(is, new MySAXHandler()); 
		} catch (ParserConfigurationException e) { 
			e.printStackTrace(); 
		} catch (SAXException e) { 
			e.printStackTrace(); 
		} catch (FileNotFoundException e) { 
			e.printStackTrace(); 
		} catch (IOException e) { 
			e.printStackTrace(); 
		} 
	} 
	
}

class MySAXHandler extends DefaultHandler { 
	boolean hasAttribute = false; 
	Attributes attributes = null; 
	
	public void startDocument() throws SAXException { 
		System.out.println("文档开始打印了"); 
	}
	
	public void endDocument() throws SAXException { 
		System.out.println("文档打印结束了"); 
	}
	
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { 
		if (qName.equals("ELs")) { 
			return;
		} 
		if (qName.equals("EL")) { 
			System.out.println(qName); 
		}
		if (attributes.getLength() > 0) { 
			this.attributes = attributes; 
			this.hasAttribute = true; 
		}
	} 
	
	public void endElement(String uri, String localName, String qName) throws SAXException { 
		if (hasAttribute && (attributes != null)) {
			for (int i = 0; i < attributes.getLength(); i++) { 
				System.out.println(attributes.getQName(0) + attributes.getValue(0)); 
			} 
		} 
	} 
	
	public void characters(char[] ch, int start, int length) throws SAXException { 
		System.out.println(new String(ch, start, length)); 
	}
	
}
 
DREI:DOM4J方式↓(性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件。
XmlDom4j.java
package com.xml;   

import java.io.File;   
import java.io.FileWriter;   
import java.io.IOException;   
import java.io.Writer;   
import java.util.Iterator;   

import org.dom4j.Document;   
import org.dom4j.DocumentException;   
import org.dom4j.DocumentHelper;   
import org.dom4j.Element;   
import org.dom4j.io.SAXReader;   
import org.dom4j.io.XMLWriter;   
/**  
 *   
 * @author 夜月  
 * Dom4j 生成XML文档与解析XML文档  
 */  
public class XmlDom4j{   
	
	public void createXml(String fileName) {   
		Document document = DocumentHelper.createDocument();   
		Element ELs = document.addElement("ELs");   
		Element EL = ELs.addElement("EL");  
		
		Element name = EL.addElement("name");   
		name.setText("夜月");
		
		Element sex = EL.addElement("sex");   
		sex.setText("M");
		
		Element age = EL.addElement("age");   
		age.setText("23");   
		try {   
			Writer fileWriter = new FileWriter(fileName);   
			XMLWriter xmlWriter = new XMLWriter(fileWriter);   
			xmlWriter.write(document);   
			xmlWriter.close();   
		} catch (IOException e) {   
			System.out.println(e.getMessage());   
		}   
	}   
	
	public void parseXml(String fileName) {   
		File inputXml=new File(fileName);   
		SAXReader saxReader = new SAXReader();   
		try {   
			Document document = saxReader.read(inputXml);   
			Element ELs = document.getRootElement();   
			for(Iterator i = ELs.elementIterator(); i.hasNext();){   
				Element EL = (Element) i.next();   
				for(Iterator j = EL.elementIterator(); j.hasNext();){   
					Element node = (Element) j.next();   
					System.out.println(node.getName()+":"+node.getText());   
				}   
			}   
		} catch (DocumentException e) {   
			System.out.println(e.getMessage());   
		}   
		System.out.println("dom4j parserXml");   
	}   
	
}   
 
VIER:JDOM方式↓(优点:20-80原则,极大减少了代码量。使用场合:要实现的功能简单,如解析、创建等,但在底层,JDOM还是使用SAX(最常用)、DOM、Xanan文档。为减少DOM、SAX的编码量,而出现了JDOM。
XmlJDOM.java
package com.xml;   

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

import org.jdom.Document;   
import org.jdom.Element;   
import org.jdom.JDOMException;   
import org.jdom.input.SAXBuilder;   
import org.jdom.output.XMLOutputter;   
/**  
 *   
 * @author 夜月
 * JDOM 生成与解析XML文档  
 *   
 */  
public class XmlJDOM {   
	
	public void createXml(String fileName) {   
		Document document;   
		Element root = new Element("Els");   
		document = new Document(root);   
		Element EL = new Element("EL");   
		root.addContent(EL);   
		
		Element name=new Element("name");   
		name.setText("夜月");   
		EL.addContent(name);  
		
		Element sex=new Element("sex");   
		sex.setText("M");   
		EL.addContent(sex);   
		
		Element age=new Element("age");   
		age.setText("23");   
		EL.addContent(age); 
		
		XMLOutputter XMLOut = new XMLOutputter();   
		try {   
			XMLOut.output(document, new FileOutputStream(fileName));   
		} catch (FileNotFoundException e) {   
			e.printStackTrace();   
		} catch (IOException e) {   
			e.printStackTrace();   
		}   
		
	}   
	
	public void parseXml(String fileName) {   
		SAXBuilder builder = new SAXBuilder(false);    
		try {   
			Document document = builder.build(fileName);   
			Element ELs = document.getRootElement();    
			List ELList = ELs.getChildren("EL");   
			for(int i=0;i<ELList.size();i++){
				Element EL = (Element)ELList.get(i);
				for(int j=0;j<EL.getContentSize();j++){
					List ELInfo = EL.getChildren();   
					System.out.println(((Element)ELInfo.get(j)).getName()+":"+((Element)ELInfo.get(j)).getValue());   
				}   
			}   
		} catch (JDOMException e) {   
			e.printStackTrace();   
		} catch (IOException e) {   
			e.printStackTrace();   
		}    
	}   
	
}