java遍歷讀取xml文件內(nèi)容
本文實(shí)例講解了java遍歷讀取xml文件內(nèi)容的詳細(xì)代碼,分享給大家供大家參考,具體內(nèi)容如下
package test; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Iterator; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMAttribute; import org.apache.axiom.om.OMComment; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMDataSource; import org.apache.axiom.om.OMDocType; import org.apache.axiom.om.OMDocument; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMProcessingInstruction; import org.apache.axiom.om.OMSourcedElement; import org.apache.axiom.om.OMText; import org.apache.axiom.om.OMXMLParserWrapper; import org.apache.axiom.om.impl.builder.StAXOMBuilder; import org.xml.sax.helpers.XMLReaderFactory; public class Axiomtest { public static void main(String[] args) throws FileNotFoundException, Throwable { // read xml FileInputStream xmlFile = new FileInputStream("line-item2.xml"); XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(xmlFile); // 還需要StAXOMBuilder對(duì)象 StAXOMBuilder builder = new StAXOMBuilder(parser); OMElement doc = builder.getDocumentElement(); // 讀到<fool></fool> OMElement cre = doc.getFirstChildWithName(new QName("student")); //讀到<student> OMElement cre1 = cre.getFirstChildWithName(new QName("id")); // 讀到<id></id> System.out.println(cre1.getLocalName()+":"+cre1.getText()); cre1 = cre.getFirstChildWithName(new QName("name")); // 讀到<name></name> System.out.println(cre1.getLocalName()+":"+cre1.getText()); cre1 = cre.getFirstChildWithName(new QName("age")); // 讀到<age></age> System.out.println(cre1.getLocalName()+":"+cre1.getText()); cre1 = cre.getFirstChildWithName(new QName("sex")); // 讀到<sex></sex> System.out.println(cre1.getLocalName()+":"+cre1.getText()); cre1 = cre.getFirstChildWithName(new QName("message")); // 讀到<sex></sex> System.out.println(cre1.getLocalName()+":"+cre1.getText()); System.out.println("------------------------------1"); Iterator<OMElement> iter = doc.getChildElements(); while(iter.hasNext()){ OMElement temp = iter.next(); System.out.println("===================="); System.out.println(temp.getLocalName()); // System.out.println(temp.getText()); if(temp.getLocalName().equals("student")){ Iterator<OMElement> iter1 = temp.getChildElements(); System.out.println("----------------"); while(iter1.hasNext()){ OMElement temp1 = iter1.next(); System.out.println(temp1.getLocalName()+":"+temp1.getText()); } } } System.out.println("!!!!!!!!!!!!!"); FileInputStream file = new FileInputStream("line-item2.xml"); XMLStreamReader read = XMLInputFactory.newInstance().createXMLStreamReader(file); StAXOMBuilder sta = new StAXOMBuilder(read); OMElement all = sta.getDocumentElement(); Iterator<OMElement> ite1 = all.getChildElements(); while(ite1.hasNext()){ OMElement temp = ite1.next(); if(temp.getLocalName().equals("student")){ Iterator<OMElement> ite2 = temp.getChildElements(); while(ite2.hasNext()){ OMElement temp1 = ite2.next(); System.out.println(temp1.getLocalName()+":"+temp1.getText()); } } } // write xml OMFactory factory = OMAbstractFactory.getOMFactory(); //建立doc節(jié)點(diǎn),doc節(jié)點(diǎn)會(huì)和下面的root節(jié)點(diǎn)合并 OMDocument dod = factory.createOMDocument(); //建立root節(jié)點(diǎn) OMElement root = factory.createOMElement("root","",""); OMElement add = factory.createOMElement("dabi","",""); //建立兩個(gè)普通節(jié)點(diǎn) OMElement stu = factory.createOMElement("student","",""); stu.addChild(factory.createOMText("mac")); OMElement tea = factory.createOMElement("teacher","",""); tea.addChild(factory.createOMText("silly")); //構(gòu)建樹,將兩個(gè)普通節(jié)點(diǎn)連到root節(jié)點(diǎn)上 root.addChild(stu); root.addChild(tea); //構(gòu)建樹,將root節(jié)點(diǎn)連到doc節(jié)點(diǎn)上 dod.addChild(root); // 構(gòu)建writer做輸出器 XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter( new FileOutputStream("2.xml")); root.serialize(writer); // cache on writer.flush(); FileInputStream xmlFile1 = new FileInputStream("2.xml"); XMLStreamReader parser1 = XMLInputFactory.newInstance().createXMLStreamReader(xmlFile1); StAXOMBuilder builder1 = new StAXOMBuilder(parser1); OMElement doc1 = builder1.getDocumentElement(); Iterator<OMElement> iter1 = doc1.getChildElements(); while(iter1.hasNext()){ OMElement temp = iter1.next(); System.out.println("===================="); System.out.println(temp.getLocalName()+":"+temp.getText()); } System.out.println("!!!!!!!!"); OMFactory omf = OMAbstractFactory.getOMFactory(); // OMDocument od = omf.createOMDocument(); OMElement root1 = omf.createOMElement("root","",""); OMElement name = omf.createOMElement("name","",""); OMElement sex = omf.createOMElement("sexy","",""); sex.addChild(omf.createOMText("man")); name.addChild(omf.createOMText("dabi")); root1.addChild(sex); root1.addChild(name); // od.addChild(root1); XMLStreamWriter xmlw = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream("3.xml")); root1.serialize(xmlw); xmlw.flush(); } }
<?xml version="1.0" encoding="UTF-8"?> <fool> <student> <name>mac</name> <id>12</id> <age>33</age> <sex>male</sex> <message>hello world</message> </student> <student> <name>silly</name> <id>5</id> <age>12</age> <sex>female</sex> </student> <teacher> <name>Mr. Jones</name> <id>2</id> <age>31</age> <sex>male</sex> </teacher> <student> <name>macy</name> <id>2</id> <age>40</age> <sex>female</sex> </student> <student> <name>tom</name> <id>32</id> <age>31</age> <sex>male</sex> </student> <message>hello world</message> </fool>
再分享一例: 用JAVA讀取XML文件
解析XML的步驟如下:
- 1.創(chuàng)建DocumentBuilder工廠
- 2.創(chuàng)建DocumentBuilder對(duì)象
- 3.DocumentBuilder對(duì)象的parse方法得到Document對(duì)象
- 4.Document對(duì)象的getElementsByTagName得到NodeList集合
- 5.通過(guò)getFirstChild和getNextSibling進(jìn)行遍歷
用到的包:
- import javax.xml.parsers.*;
- import org.w3c.dom.*;
- import org.xml.sax.*;
用到的對(duì)象:
- DocumentBuilderFactory:創(chuàng)建DocumentBuilder的抽象工廠
- DocumentBuilder:可以從 XML 獲取一個(gè) Document
- Document:提供供對(duì)文檔數(shù)據(jù)的基本訪問(wèn)
用到的方法:
- DocumentBuilder.parse(String)':將給定 URI 的內(nèi)容解析為一個(gè) XML 文檔,并且返回一個(gè)新的 DOM Document對(duì)象
- Document.getElementsByTagName(String)':返回具有給定標(biāo)記名稱的所有 Element 的 NodeList
- Element.getAttribute(String)':通過(guò)名稱獲得屬性值
下面來(lái)解析一個(gè)XML文件
import javax.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.*; public class Test { public static void main(String[] args) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse("pet2.xml"); NodeList dogList = doc.getElementsByTagName("dog"); System.out.println("共有" + dogList.getLength() + "個(gè)dog節(jié)點(diǎn)"); for (int i = 0; i < dogList.getLength(); i++) { Node dog = dogList.item(i); Element elem = (Element) dog; System.out.println("id:" + elem.getAttribute("id")); for (Node node = dog.getFirstChild(); node != null; node = node.getNextSibling()) { if (node.getNodeType() == Node.ELEMENT_NODE) { String name = node.getNodeName(); String value = node.getFirstChild().getNodeValue(); System.out.print(name + ":" + value + "\t"); } } System.out.println(); } } catch (Exception e) { e.printStackTrace(); } } }
XML文件
<pets> <dogs> <dog id="1"> <name>YAYA</name> <health>100</health> <love>0</love> <strain>酷酷的雪娜瑞</strain> </dog> <dog id="2"> <name>OUOU</name> <health>90</health> <love>15</love> <strain>聰明的拉布拉多犬</strain> </dog> </dogs> <penguins> <penguin id="3"> <name>QQ</name> <health>100</health> <love>20</love> <sex>Q仔</sex> </penguin> </penguins> </pets>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。
- jQuery實(shí)現(xiàn)遍歷XML節(jié)點(diǎn)和屬性的方法示例
- python xml.etree.ElementTree遍歷xml所有節(jié)點(diǎn)實(shí)例詳解
- php遍歷解析xml字符串的方法
- ajax遍歷xml文檔的方法
- PHP遍歷XML文檔所有節(jié)點(diǎn)的方法
- python目錄操作之python遍歷文件夾后將結(jié)果存儲(chǔ)為xml
- asp.net Linq To Xml上手Descendants、Elements遍歷節(jié)點(diǎn)
- Dom遍歷XML的一個(gè)例子,結(jié)果為樹狀結(jié)構(gòu)
- Xml中使用foreach遍歷對(duì)象實(shí)現(xiàn)代碼
相關(guān)文章
使用cmd根據(jù)WSDL網(wǎng)址生成java客戶端代碼的實(shí)現(xiàn)
這篇文章主要介紹了使用cmd根據(jù)WSDL網(wǎng)址生成java客戶端代碼的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-03-03IntelliJ IDEA 2020.1.2激活工具下載及破解方法免費(fèi)可用至2089年(強(qiáng)烈推薦)
這篇文章主要介紹了IntelliJ IDEA 2020.1.2激活工具下載及破解方法免費(fèi)可用至2089年(強(qiáng)烈推薦),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09如何解決SpringBoot集成百度UEditor圖片上傳后直接訪問(wèn)404
在本篇文章里小編給大家整理的是一篇關(guān)于如何解決SpringBoot集成百度UEditor圖片上傳后直接訪問(wèn)404相關(guān)文章,需要的朋友們學(xué)習(xí)下。2019-11-11詳解tryAcquire()、addWaiter()、acquireQueued()
這篇文章主要tryAcquire()、addWaiter()、acquireQueued()的用法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03java 通過(guò) SmbFile 類操作共享文件夾的示例
這篇文章主要介紹了java 通過(guò) SmbFile 類操作共享文件夾,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-02-02SpringBoot+SpringSecurity+jwt實(shí)現(xiàn)驗(yàn)證
本文主要介紹了SpringBoot+SpringSecurity+jwt實(shí)現(xiàn)驗(yàn)證,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07淺談Mybatis中resultType為hashmap的情況
這篇文章主要介紹了淺談Mybatis中resultType為hashmap的情況,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-12-12