search
HomeJavajavaTutorialFour methods for reading XML files in java (collection)

下面小编就为大家带来一篇java读取XML文件的四种方法总结(必看篇)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

下面基于这四种方式来读取XML文件。

第一,以DOM的方式实现。

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的方式实现。

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解析结束");
  }
  @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的方式实现。

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的方式实现。

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("子节点:" + child.getName());
        }
      }
    }catch (DocumentException e){
      e.printStackTrace();
    }
  }
  public static void main(String[] args){
    DOM4JTest dom4JTest = new DOM4JTest();
    dom4JTest.parseXML();
  }
}

The above is the detailed content of Four methods for reading XML files in java (collection). 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
Java Platform Independence: Differences between OSJava Platform Independence: Differences between OSMay 16, 2025 am 12:18 AM

There are subtle differences in Java's performance on different operating systems. 1) The JVM implementations are different, such as HotSpot and OpenJDK, which affect performance and garbage collection. 2) The file system structure and path separator are different, so it needs to be processed using the Java standard library. 3) Differential implementation of network protocols affects network performance. 4) The appearance and behavior of GUI components vary on different systems. By using standard libraries and virtual machine testing, the impact of these differences can be reduced and Java programs can be ensured to run smoothly.

Java's Best Features: From Object-Oriented Programming to SecurityJava's Best Features: From Object-Oriented Programming to SecurityMay 16, 2025 am 12:15 AM

Javaoffersrobustobject-orientedprogramming(OOP)andtop-notchsecurityfeatures.1)OOPinJavaincludesclasses,objects,inheritance,polymorphism,andencapsulation,enablingflexibleandmaintainablesystems.2)SecurityfeaturesincludetheJavaVirtualMachine(JVM)forsand

Best Features for Javascript vs JavaBest Features for Javascript vs JavaMay 16, 2025 am 12:13 AM

JavaScriptandJavahavedistinctstrengths:JavaScriptexcelsindynamictypingandasynchronousprogramming,whileJavaisrobustwithstrongOOPandtyping.1)JavaScript'sdynamicnatureallowsforrapiddevelopmentandprototyping,withasync/awaitfornon-blockingI/O.2)Java'sOOPf

Java Platform Independence: Benefits, Limitations, and ImplementationJava Platform Independence: Benefits, Limitations, and ImplementationMay 16, 2025 am 12:12 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM)andbytecode.1)TheJVMinterpretsbytecode,allowingthesamecodetorunonanyplatformwithaJVM.2)BytecodeiscompiledfromJavasourcecodeandisplatform-independent.However,limitationsincludepotentialp

Java: Platform Independence in the real wordJava: Platform Independence in the real wordMay 16, 2025 am 12:07 AM

Java'splatformindependencemeansapplicationscanrunonanyplatformwithaJVM,enabling"WriteOnce,RunAnywhere."However,challengesincludeJVMinconsistencies,libraryportability,andperformancevariations.Toaddressthese:1)Usecross-platformtestingtools,2)

JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

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

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.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software