search

Read XML file

Jun 23, 2017 pm 03:54 PM
documentread

   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 
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 
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 }</attribute></element>
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 }</attribute>
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
How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

What does 'platform independence' mean in the context of Java?What does 'platform independence' mean in the context of Java?Apr 23, 2025 am 12:05 AM

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Can Java applications still encounter platform-specific bugs or issues?Can Java applications still encounter platform-specific bugs or issues?Apr 23, 2025 am 12:03 AM

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

How does cloud computing impact the importance of Java's platform independence?How does cloud computing impact the importance of Java's platform independence?Apr 22, 2025 pm 07:05 PM

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

What role has Java's platform independence played in its widespread adoption?What role has Java's platform independence played in its widespread adoption?Apr 22, 2025 pm 06:53 PM

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

How do containerization technologies (like Docker) affect the importance of Java's platform independence?How do containerization technologies (like Docker) affect the importance of Java's platform independence?Apr 22, 2025 pm 06:49 PM

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)