Home  >  Article  >  Java  >  Read XML file

Read XML file

巴扎黑
巴扎黑Original
2017-06-23 15:54:241398browse

   JAVA操作XML文档主要有四种方式,分别是DOM、SAX、JDOM和DOM4J,DOM和SAX是官方提供的,而JDOM和DOM4J则是引用第三方库的,其中用的最多的是DOM4J方式。运行效率和内存使用方面最优的是SAX,但是由于SAX是基于事件的方式,所以SAX无法在编写XML的过程中对已编写内容进行修改,但对于不用进行频繁修改的需求,还是应该选择使用SAX。

   下面基于这四种方式来读取XML文件。
 
   第一,以DOM的方式实现。
 1 package xmls; 2 import org.w3c.dom.Document; 3 import org.w3c.dom.Element; 4 import org.w3c.dom.Node; 5 import org.w3c.dom.NodeList; 6 import org.xml.sax.SAXException; 7 import javax.xml.parsers.DocumentBuilder; 8 import javax.xml.parsers.DocumentBuilderFactory; 9 import javax.xml.parsers.ParserConfigurationException;10 import java.io.File;11 import java.io.IOException;12 /**13  * Created by lenovo on 2017-6-3.14  */15 public class DOMReadDemo {16     public static void main(String[] args){17         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();18         try{19             DocumentBuilder db = dbf.newDocumentBuilder();20             Document document = db.parse("src/xmls/DOM.xml");21             NodeList booklist = document.getElementsByTagName("book");22             for(int i = 0; i < booklist.getLength(); i++){23                 System.out.println("--------第" + (i+1) + "本书----------");24                 Element ele = (Element) booklist.item(i);25                 NodeList childNodes= ele.getChildNodes();26                 for(int j = 0; j < childNodes.getLength(); j++){27                     Node n = childNodes.item(j);28                     if(n.getNodeName() != "#text"){29                         System.out.println(n.getNodeName() + ":" + n.getTextContent());30                     }31                 }32                 System.out.println("---------------------------------");33             }34         }catch (ParserConfigurationException e){35             e.printStackTrace();36         }catch (IOException e){37             e.printStackTrace();38         }catch (SAXException e){39             e.printStackTrace();40         }41     }42 }
View Code

第二,以SAX的方式实现。

 1 package xmls; 2 import javax.xml.parsers.SAXParser; 3 import javax.xml.parsers.SAXParserFactory; 4 /** 5  * Created by lenovo on 2017-6-1. 6  */ 7 public class xmlTest2 { 8     public static void main(String[] args){ 9         SAXParserFactory spf = SAXParserFactory.newInstance();10         try{11             SAXParser sp = spf.newSAXParser();12             SAXParserHandler handler = new SAXParserHandler();13             sp.parse("src\\xmls\\book.xml", handler);14         }catch (Exception e){15             e.printStackTrace();16         }17     }18 }
View Code
 1 package xmls; 2 import org.xml.sax.Attributes; 3 import org.xml.sax.SAXException; 4 import org.xml.sax.helpers.DefaultHandler; 5 /** 6  * Created by lenovo on 2017-6-1. 7  */ 8 public class SAXParserHandler extends DefaultHandler { 9     @Override10     public void startDocument() throws SAXException {11         super.startDocument();12         System.out.println("SAX解析开始");13     }14     @Override15     public void endDocument() throws SAXException {16         super.endDocument();17         System.out.println("SAX解析结束");18     }19     @Override20     public void startElement(String s, String s1, String s2, Attributes attributes) throws SAXException {21         super.startElement(s, s1, s2, attributes);22         System.out.println(s2);23         for(int i = 0; i < attributes.getLength(); i++){24             String name = attributes.getQName(i);25             String value = attributes.getValue(name);26             System.out.println("属性值:" + name + "=" + value);27         }28     }29     @Override30     public void endElement(String s, String s1, String s2) throws SAXException {31         super.endElement(s, s1, s2);32         if(s2.equals("book")){33             System.out.println("-----------------------");34         }35     }36     @Override37     public void characters(char[] ch, int start, int length) throws SAXException {38         super.characters(ch, start, length);39         String value = new String(ch, start, length);40         if(value.trim().equals("")){41             return;42         }43         System.out.println(value);44     }45 }
View Code

第三,以JDOM的方式实现。

 1 package xmls; 2 import org.jdom2.Attribute; 3 import org.jdom2.Document; 4 import org.jdom2.Element; 5 import org.jdom2.JDOMException; 6 import org.jdom2.input.JDOMParseException; 7 import org.jdom2.input.SAXBuilder; 8 import java.io.*; 9 import java.util.List;10 /**11  * Created by lenovo on 2017-6-2.12  */13 public class JDOMTest {14     public static void main(String[] args){15         SAXBuilder saxBuilder = new SAXBuilder();16         InputStream in;17         try{18             in = new FileInputStream(new File("src\\xmls\\book.xml"));19             Document document = saxBuilder.build(in);20             Element rootElement = document.getRootElement();21             List<Element> bookList = rootElement.getChildren();22             for(Element book: bookList){23                 System.out.println("第" + (bookList.indexOf(book)+1) + "本书!");24                 List<Attribute> attrs = book.getAttributes();25                 for(Attribute attr: attrs){26                     System.out.println(attr.getName() + "=" + attr.getValue());27                 }28                 for(Element item: book.getChildren()){29                     System.out.println(item.getName() + ":" + item.getValue());30                 }31                 System.out.println("------------------------------------");32             }33         }catch (FileNotFoundException e){34             e.printStackTrace();35         }catch (JDOMException e){36             e.printStackTrace();37         }catch (IOException e){38             e.printStackTrace();39         }40     }41 }
View Code

 

    第四,以DOM4J的方式实现。

 1 package xmls; 2 import org.dom4j.*; 3 import org.dom4j.io.OutputFormat; 4 import org.dom4j.io.SAXReader; 5 import org.dom4j.io.XMLWriter; 6 import java.io.File; 7 import java.io.FileOutputStream; 8 import java.io.IOException; 9 import java.util.Iterator;10 import java.util.List;11 /**12  * Created by lenovo on 2017-6-2.13  */14 public class DOM4JTest {15     public void parseXML(){16         SAXReader saxReader = new SAXReader();17         try{18             Document document = saxReader.read(new File("src\\xmls\\book.xml"));19             Element rootElement = document.getRootElement();20             Iterator it = rootElement.elementIterator();21             while (it.hasNext()){22                 Element book = (Element)it.next();23                 List<Attribute> attrs = book.attributes();24                 for(Attribute attr: attrs){25                     System.out.println("属性名:" + attr.getName() + "---- 属性值:" + attr.getValue() );26                 }27                 Iterator cit = book.elementIterator();28                 while (cit.hasNext()){29                     Element child = (Element) cit.next();30                     System.out.println("子节点:" + child.getName());31                 }32             }33         }catch (DocumentException e){34             e.printStackTrace();35         }36     }37     public static void main(String[] args){38         DOM4JTest dom4JTest = new DOM4JTest();39         dom4JTest.parseXML();40     }41 }
View Code

 

 

The above is the detailed content of Read XML file. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:java process controlNext article:java process control

Related articles

See more