java讀取XML文件的四種方法總結(jié)(必看篇)
JAVA操作XML文檔主要有四種方式,分別是DOM、SAX、JDOM和DOM4J,DOM和SAX是官方提供的,而JDOM和DOM4J則是引用第三方庫的,其中用的最多的是DOM4J方式。運行效率和內(nèi)存使用方面最優(yōu)的是SAX,但是由于SAX是基于事件的方式,所以SAX無法在編寫XML的過程中對已編寫內(nèi)容進行修改,但對于不用進行頻繁修改的需求,還是應(yīng)該選擇使用SAX。
下面基于這四種方式來讀取XML文件。
第一,以DOM的方式實現(xiàn)。
package xmls;
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;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
/**
* Created by lenovo on 2017-6-3.
*/
public class DOMReadDemo {
public static void main(String[] args){
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try{
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse("src/xmls/DOM.xml");
NodeList booklist = document.getElementsByTagName("book");
for(int i = 0; i < booklist.getLength(); i++){
System.out.println("--------第" + (i+1) + "本書----------");
Element ele = (Element) booklist.item(i);
NodeList childNodes= ele.getChildNodes();
for(int j = 0; j < childNodes.getLength(); j++){
Node n = childNodes.item(j);
if(n.getNodeName() != "#text"){
System.out.println(n.getNodeName() + ":" + n.getTextContent());
}
}
System.out.println("---------------------------------");
}
}catch (ParserConfigurationException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (SAXException e){
e.printStackTrace();
}
}
}
第二,以SAX的方式實現(xiàn)。
package xmls;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
/**
* Created by lenovo on 2017-6-1.
*/
public class xmlTest2 {
public static void main(String[] args){
SAXParserFactory spf = SAXParserFactory.newInstance();
try{
SAXParser sp = spf.newSAXParser();
SAXParserHandler handler = new SAXParserHandler();
sp.parse("src\\xmls\\book.xml", handler);
}catch (Exception e){
e.printStackTrace();
}
}
}
package xmls;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Created by lenovo on 2017-6-1.
*/
public class SAXParserHandler extends DefaultHandler {
@Override
public void startDocument() throws SAXException {
super.startDocument();
System.out.println("SAX解析開始");
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
System.out.println("SAX解析結(jié)束");
}
@Override
public void startElement(String s, String s1, String s2, Attributes attributes) throws SAXException {
super.startElement(s, s1, s2, attributes);
System.out.println(s2);
for(int i = 0; i < attributes.getLength(); i++){
String name = attributes.getQName(i);
String value = attributes.getValue(name);
System.out.println("屬性值:" + name + "=" + value);
}
}
@Override
public void endElement(String s, String s1, String s2) throws SAXException {
super.endElement(s, s1, s2);
if(s2.equals("book")){
System.out.println("-----------------------");
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
String value = new String(ch, start, length);
if(value.trim().equals("")){
return;
}
System.out.println(value);
}
}
第三,以JDOM的方式實現(xiàn)。
package xmls;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.JDOMParseException;
import org.jdom2.input.SAXBuilder;
import java.io.*;
import java.util.List;
/**
* Created by lenovo on 2017-6-2.
*/
public class JDOMTest {
public static void main(String[] args){
SAXBuilder saxBuilder = new SAXBuilder();
InputStream in;
try{
in = new FileInputStream(new File("src\\xmls\\book.xml"));
Document document = saxBuilder.build(in);
Element rootElement = document.getRootElement();
List<Element> bookList = rootElement.getChildren();
for(Element book: bookList){
System.out.println("第" + (bookList.indexOf(book)+1) + "本書!");
List<Attribute> attrs = book.getAttributes();
for(Attribute attr: attrs){
System.out.println(attr.getName() + "=" + attr.getValue());
}
for(Element item: book.getChildren()){
System.out.println(item.getName() + ":" + item.getValue());
}
System.out.println("------------------------------------");
}
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (JDOMException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
}
第四,以DOM4J的方式實現(xiàn)。
package xmls;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
/**
* Created by lenovo on 2017-6-2.
*/
public class DOM4JTest {
public void parseXML(){
SAXReader saxReader = new SAXReader();
try{
Document document = saxReader.read(new File("src\\xmls\\book.xml"));
Element rootElement = document.getRootElement();
Iterator it = rootElement.elementIterator();
while (it.hasNext()){
Element book = (Element)it.next();
List<Attribute> attrs = book.attributes();
for(Attribute attr: attrs){
System.out.println("屬性名:" + attr.getName() + "---- 屬性值:" + attr.getValue() );
}
Iterator cit = book.elementIterator();
while (cit.hasNext()){
Element child = (Element) cit.next();
System.out.println("子節(jié)點:" + child.getName());
}
}
}catch (DocumentException e){
e.printStackTrace();
}
}
public static void main(String[] args){
DOM4JTest dom4JTest = new DOM4JTest();
dom4JTest.parseXML();
}
}
以上這篇java讀取XML文件的四種方法總結(jié)(必看篇)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
JavaWeb JDBC + MySql 通訊錄實現(xiàn)簡單的增刪改查功能案例詳解
這篇文章主要介紹了JavaWeb JDBC + MySql 通訊錄實現(xiàn)簡單的增刪改查功能,結(jié)合具體案例形式詳細分析了JavaWeb JDBC + MySql數(shù)據(jù)庫連接、增刪改查等相關(guān)操作技巧與注意事項,需要的朋友可以參考下2019-08-08
FactoryBean?BeanFactory方法使用示例詳解講解
這篇文章主要為大家介紹了FactoryBean?BeanFactory方法使用示例詳解講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12
MyBatis-plus處理存儲json數(shù)據(jù)過程
文章介紹MyBatis-Plus 3.4.21處理對象與集合的差異:對象可用內(nèi)置Handler配合autoResultMap,集合需自定義處理器繼承FastjsonTypeHandler并重寫parse方法,同時需明確指定類類型及XML中的resultMap以解決轉(zhuǎn)換問題2025-08-08
mybatis-plus 處理大數(shù)據(jù)插入太慢的解決
這篇文章主要介紹了mybatis-plus 處理大數(shù)據(jù)插入太慢的解決,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12

