最牛視頻網(wǎng)站建設(shè)常州網(wǎng)絡(luò)推廣seo
1 在Java中解析XML文件共有四種方式
- A、DOM方式解析XML數(shù)據(jù)
樹(shù)結(jié)構(gòu),有助于更好地理解、掌握,代碼易于編寫(xiě),在解析過(guò)程中樹(shù)結(jié)構(gòu)是保存在內(nèi)存中,方便修改
- B、SAX方式解析
采用事件驅(qū)動(dòng)模式,對(duì)內(nèi)存消耗比較小,適用于僅處理xml中的數(shù)據(jù)時(shí)使用
- C、JDOM方式解析
大量采用了 Collections 類
- D、DOM4J方式解析
JDOM的一種智能分支,合并了許多超出基本XML文檔表示的功能;
性能優(yōu)越,靈活性好,功能強(qiáng)大,極端易用。
2 要處理的XML文件
<?xml version="1.0" encoding="UTF-8"?> <books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><book id="1001"><name>JAVA 高級(jí)編程</name><author>張三</author><price>85.72</price></book><book id="1002"><name>C++和C#</name><author>李失失</author><price>125.73</price></book> </books>
3 DOM方式解析XML數(shù)據(jù)的步驟
a. 創(chuàng)建一個(gè)DocumentBuilderFactory對(duì)象
b. 創(chuàng)建一個(gè)DocumentBuilder對(duì)象
c. 通過(guò)DocumentBuilder的parse()方法,得到Document對(duì)象
d. 通過(guò)getElementsByTagName()方法,獲取節(jié)點(diǎn)的列表
e. 使用for循環(huán)遍歷節(jié)點(diǎn)
f. 得到所有節(jié)點(diǎn)的屬性和屬性值
g. 得到所有節(jié)點(diǎn)的節(jié)點(diǎn)名和節(jié)點(diǎn)值
import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException;public class TestDom4Xml {public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {//創(chuàng)建一個(gè)DocumentBuilderFactory對(duì)象DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();//創(chuàng)建一個(gè)DocumentBuilder對(duì)象DocumentBuilder db = dbf.newDocumentBuilder();//通過(guò)DocumentBuilder的parse()方法,得到Document對(duì)象Document doc = db.parse("book.xml");//通過(guò)getElementsByTagName()方法,獲取節(jié)點(diǎn)的列表NodeList nodelist = doc.getElementsByTagName("book");System.out.println(nodelist.getLength());//使用for循環(huán)遍歷節(jié)點(diǎn)for(int i=0;i<nodelist.getLength();i++){Node node = nodelist.item(i);//得到所有節(jié)點(diǎn)屬性和屬性值的對(duì)象NamedNodeMap nnm = node.getAttributes();for(int j=0;j<nnm.getLength();j++){Node sub_node = nnm.item(j);//得到所有節(jié)點(diǎn)的屬性和屬性值System.out.println(sub_node.getNodeName() + " : " + sub_node.getNodeValue());}//得到所有節(jié)點(diǎn)的子節(jié)點(diǎn)NodeList childlist = node.getChildNodes();for(int j=0;j<childlist.getLength();j++){Node sub_node = childlist.item(j);//獲取節(jié)點(diǎn)類型short type = sub_node.getNodeType();//判斷節(jié)點(diǎn)類型是否不為#text,因會(huì)將前一標(biāo)簽的末尾>與下一標(biāo)簽的開(kāi)頭<之間的字符,標(biāo)記為#text//因此這里需要進(jìn)行判斷if(type == Node.ELEMENT_NODE){//得到所有節(jié)點(diǎn)的節(jié)點(diǎn)名和節(jié)點(diǎn)值System.out.println(sub_node.getNodeName() + " : " + sub_node.getTextContent());}}}} }
輸出結(jié)果如下
2
id : 1001
name : JAVA 高級(jí)編程
author : 張三
price : 85.72
id : 1002
name : C++和C#
author : 李失失
price : 125.73
4 SAX方式解析XML文件
4.1 創(chuàng)建DeaultHandler子類,用來(lái)解析XML文檔
import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler;public class BookDefaultHandler extends DefaultHandler {/*** 解析xml文檔時(shí)調(diào)用*/public void startDocument() throws SAXException {System.out.println("開(kāi)始解析XML文檔");super.startDocument();}/*** 解析xml文檔結(jié)束時(shí)調(diào)用*/public void endDocument() throws SAXException {super.endDocument();System.out.println("完成解析XML文檔");}/*** 解析XML文檔節(jié)點(diǎn)開(kāi)始時(shí)使用*/public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {super.startElement(uri, localName, qName, attributes);//判斷如果是 book節(jié)點(diǎn),獲取節(jié)點(diǎn)屬性和屬性值if(qName.equals("book")){//獲取當(dāng)前屬性的數(shù)量int len = attributes.getLength();//循環(huán)獲取每個(gè)屬性for(int i=0;i<len;i++){//屬性名稱String name = attributes.getQName(i);//屬性值String value = attributes.getValue(i);System.out.println("屬性名稱: " + name + "\t屬性值: " + value);}}else if(!"books".equals(qName) && !"book".equals(qName)){System.out.print("節(jié)點(diǎn)的名稱:" + qName + "\t");}}/*** 解析XML文檔節(jié)點(diǎn)結(jié)束時(shí)使用*/public void endElement(String uri, String localName, String qName) throws SAXException {super.endElement(uri, localName, qName);}/*** 解析節(jié)點(diǎn)文本內(nèi)容*/public void characters(char[] ch, int start, int length) throws SAXException {super.characters(ch, start, length);//將節(jié)點(diǎn)文本轉(zhuǎn)為字符串String value = new String(ch, start, length);//排除空數(shù)據(jù),并輸出節(jié)點(diǎn)文本if(!"".equals(value.trim())){System.out.println(value);}} }
4.2 SAX方式解析XML數(shù)據(jù)的步驟
a. 創(chuàng)建SAXParserFactory對(duì)象
b. 創(chuàng)建SAXParser對(duì)象(作為解析器)
c. 創(chuàng)建DefaultHandler子類對(duì)象
d. 調(diào)用parse方法
import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException;public class TestSax4Xml {public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {//a. 創(chuàng)建SAXParserFactory對(duì)象SAXParserFactory spf = SAXParserFactory.newInstance();//b. 創(chuàng)建SAXParser對(duì)象(作為解析器)SAXParser sp = spf.newSAXParser();//c. 創(chuàng)建DefaultHandler子類對(duì)象BookDefaultHandler bdh = new BookDefaultHandler();//d. 調(diào)用SAXParser對(duì)象的parse方法sp.parse("book.xml", bdh);} }
4.3 輸出結(jié)果
開(kāi)始解析XML文檔
屬性名稱: id 屬性值: 1001
節(jié)點(diǎn)的名稱:name JAVA 高級(jí)編程
節(jié)點(diǎn)的名稱:author 張三
節(jié)點(diǎn)的名稱:price 85.72
屬性名稱: id 屬性值: 1002
節(jié)點(diǎn)的名稱:name C++和C#
節(jié)點(diǎn)的名稱:author 李失失
節(jié)點(diǎn)的名稱:price 125.73
完成解析XML文檔
5 JDOM方式解析XML數(shù)據(jù)
5.1 步驟
a. 創(chuàng)建SAXBuilder對(duì)象
b. 調(diào)用build方法,通過(guò)IO流得到Document對(duì)象
c. 獲取根節(jié)點(diǎn)
d. 獲取根節(jié)點(diǎn)下直接子節(jié)點(diǎn)的集合
e. 遍歷集合
import java.io.FileInputStream; import java.io.IOException; import java.util.List;import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder;public class TestJdom4Xml {public static void main(String[] args) throws JDOMException, IOException {//a. 創(chuàng)建SAXBuilder對(duì)象SAXBuilder sb = new SAXBuilder();//b. 調(diào)用build方法,通過(guò)OI流得到Document對(duì)象Document doc = sb.build(new FileInputStream("src/book.xml"));//c. 獲取根節(jié)點(diǎn)Element root = doc.getRootElement();//d. 獲取根節(jié)點(diǎn)下直接子節(jié)點(diǎn)的集合List<Element> books = root.getChildren();//e. 遍歷集合,獲取每一個(gè)子節(jié)點(diǎn)for(int i=0;i<books.size();i++){//獲取集合中的元素Element book = books.get(i);//獲取當(dāng)前節(jié)點(diǎn)下的屬性集合List<Attribute> atts = book.getAttributes();for(int j=0;j<atts.size();j++){//輸出屬性名稱:屬性值System.out.println(atts.get(j).getName() + "\t" + atts.get(j).getValue());}//獲取當(dāng)前節(jié)點(diǎn)下子節(jié)點(diǎn)List<Element> subEles = book.getChildren();//遍歷子節(jié)點(diǎn),獲取名稱和文本值for(Element e : subEles){System.out.println(e.getName() + "\t" + e.getValue());}}} }
5.2 輸出結(jié)果
id 1001
name JAVA 高級(jí)編程
author 張三
price 85.72
id 1002
name C++和C#
author 李失失
price 125.73
6 DOM4J解析XML
6.1 DOM4J解析XML步驟
a. 創(chuàng)建SAXReader對(duì)象
b. 調(diào)用read方法
c. 獲取根節(jié)點(diǎn)
d. 通過(guò)迭代器遍歷直接節(jié)點(diǎn)
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Iterator;import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader;public class TestDom4jXml {public static void main(String[] args) throws FileNotFoundException, DocumentException {//a. 創(chuàng)建SAXReader對(duì)象SAXReader sr = new SAXReader();//b. 調(diào)用read方法Document doc = sr.read(new FileInputStream("src/book.xml"));//c. 獲取根節(jié)點(diǎn)Element root = doc.getRootElement();//d. 通過(guò)迭代器遍歷直接節(jié)點(diǎn)for(Iterator<Element> iter=root.elementIterator();iter.hasNext();){Element book = iter.next();//獲取節(jié)點(diǎn)下所有屬性Iterator<Attribute> arrts = book.attributeIterator();//遍歷屬性信息while(arrts.hasNext()){Attribute at = arrts.next();String name = at.getName();String value = at.getValue();System.out.println("節(jié)點(diǎn)屬性:" + name + "\t" + value);}//遍歷節(jié)點(diǎn)下子節(jié)點(diǎn)Iterator<Element> subele = book.elementIterator();//獲取子節(jié)點(diǎn)下所有節(jié)點(diǎn)名稱和文本值while(subele.hasNext()){Element node = subele.next();System.out.println(node.getName() + "\t" + node.getText());}}} }
6.2 輸出結(jié)果
節(jié)點(diǎn)屬性:id 1001
name JAVA 高級(jí)編程
author 張三
price 85.72
節(jié)點(diǎn)屬性:id 1002
name C++和C#
author 李失失
price 125.73