search
HomeBackend DevelopmentXML/RSS TutorialFour ways to read xml files using dom4j

Four ways to read xml files using dom4j

The following are four ways to read xml files, each with its own use. This is what I found when I was writing a log manager. Hope it helps everyone.

First we give a simple xml file

<?xml version="1.0" ?>
<ROWDATA>

<ROW>
  <C0>1</C0>
  <EMPNO>7891</EMPNO>
  <ENAME>sdffff</ENAME>
  <JOB>job</JOB>
  <MGR></MGR>
  <HIREDATE>2010-1-1</HIREDATE>
  <SAL>5000.00</SAL>
  <COMM>1000.00</COMM>
  <DEPTNO></DEPTNO>
</ROW>

<ROW>
  <C0>2</C0>
  <EMPNO>7369</EMPNO>
  <ENAME>SMITH</ENAME>
  <JOB>CLERK</JOB>
  <MGR>7902</MGR>
  <HIREDATE>1980-12-17</HIREDATE>
  <SAL>800.00</SAL>
  <COMM></COMM>
  <DEPTNO>20</DEPTNO>
</ROW>

</ROWDATA>

The first type:

/**
  * 使用dom4j 中saxreader 获取Document容器,利用此容器的elementIterator读取xml文件
  */
 public static void readXML() throws DocumentException{
  
  SAXReader sr = new SAXReader();//获取读取xml的对象。
  Document doc = sr.read("src/com/sinojava/EMP.xml");//得到xml所在位置。然后开始读取。并将数据放入doc中
  Element el_root = doc.getRootElement();//向外取数据,获取xml的根节点。
  Iterator it = el_root.elementIterator();//从根节点下依次遍历,获取根节点下所有子节点
  
  while(it.hasNext()){//遍历该子节点
   
   Object o = it.next();//再获取该子节点下的子节点
   Element el_row = (Element)o;
   String s = el_row.getText();

   Iterator it_row = el_row.elementIterator();
   
   while(it_row.hasNext()){//遍历节点
    
    Element el_ename = (Element)it_row.next();//获取该节点下的所有数据。
    System.out.println(el_ename.getText());
   }
   //System.out.println(o);
  }
  
 }

The second type:;

/**
  * 使用elements方法进行xml的读取,相当于条件查询,可以根据不同的节点,利用for循环查询该节点下所有的数据。
  * @throws DocumentException
  */
 public static void readXML02() throws DocumentException{
  
  SAXReader sr = new SAXReader();//获取读取方式
  Document doc = sr.read("src/com/sinojava/EMP.xml");//读取xml文件,并且将数据全部存放到Document中
  Element root = doc.getRootElement();//获取根节点
  
  List list = root.elements("ROW");//根据根节点,将根节点下 row中的所有数据放到list容器中。
  for(Object obj:list){//这种遍历方式,是jdk1.5以上的版本支持的遍历方式
   Element row = (Element)obj;
   List list_row = row.elements("ENAME");//获取ENAME节点下所有的内容,存入list_row容器中
   
   for(Object objempno:list_row){
    
    Element el_empno = (Element)objempno;
    
    System.out.println(el_empno.getName()+": "+el_empno.getText());//获取节点下的数据。
    
   }
  }
 }

The third type:

/**
  * 使用适配器来完成xml的读取。
  * @param args
  * @throws DocumentException
  */
 public static void readXML04() throws DocumentException{
  
  SAXReader sr = new SAXReader();
  Document doc = sr.read("src/com/sinojava/EMP.xml");
  
  doc.accept(new VisitorSupport() {//使用观察器的子类,来完成对xml文件的读取。
   
   public void visit(Element el) {//利用观察期进行xml的读取。
    
    System.out.println(el.getName()+": "+el.getText());

   }
   
  });
 }

The fourth type:

/**
  * 使用selectNodes读取xml文件
  * @param args
  * @throws DocumentException
  */
 public static void readXML05(String elementpath) throws DocumentException{
  
  SAXReader sr = new SAXReader();
  Document doc = sr.read("src/com/sinojava/EMP.xml");
  
  List list = doc.selectNodes(elementpath);//使用selectNodes获取所要查询xml的节点。
  
  for(Object obj:list){//遍历节点,获取节点内数据。
   
   Element el = (Element)obj;
   System.out.println(el.getText());
  }
  
 }

For more related questions, please visit the PHP Chinese website: XML Video Tutorial

The above is the detailed content of Four ways to read xml files using dom4j. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
RSS: The XML-Based Format ExplainedRSS: The XML-Based Format ExplainedMay 04, 2025 am 12:05 AM

RSS is an XML-based format used to subscribe and read frequently updated content. Its working principle includes two parts: generation and consumption, and using an RSS reader can efficiently obtain information.

Inside the RSS Document: Essential XML Tags and AttributesInside the RSS Document: Essential XML Tags and AttributesMay 03, 2025 am 12:12 AM

The core structure of RSS documents includes XML tags and attributes. The specific parsing and generation steps are as follows: 1. Read XML files, process and tags. 2. Extract,,, etc. tag information. 3. Handle custom tags and attributes to ensure version compatibility. 4. Use cache and asynchronous processing to optimize performance to ensure code readability.

JSON, XML, and Data Formats: Comparing RSSJSON, XML, and Data Formats: Comparing RSSMay 02, 2025 am 12:20 AM

The main differences between JSON, XML and RSS are structure and uses: 1. JSON is suitable for simple data exchange, with a simple structure and easy to parse; 2. XML is suitable for complex data structures, with a rigorous structure but complex parsing; 3. RSS is based on XML and is used for content release, standardized but limited use.

Troubleshooting XML/RSS Feeds: Common Pitfalls and Expert SolutionsTroubleshooting XML/RSS Feeds: Common Pitfalls and Expert SolutionsMay 01, 2025 am 12:07 AM

The processing of XML/RSS feeds involves parsing and optimization, and common problems include format errors, encoding issues, and missing elements. Solutions include: 1. Use XML verification tools to check for format errors; 2. Ensure encoding consistency and use the chardet library to detect encoding; 3. Use default values ​​or skip the element when missing elements; 4. Use efficient parsers such as lxml and cache parsing results to optimize performance; 5. Pay attention to data consistency and security to prevent XML injection attacks.

Decoding RSS Documents: Reading and Interpreting FeedsDecoding RSS Documents: Reading and Interpreting FeedsApr 30, 2025 am 12:02 AM

The steps to parse RSS documents include: 1. Read the XML file, 2. Use DOM or SAX to parse XML, 3. Extract headings, links and other information, and 4. Process data. RSS documents are XML-based formats used to publish updated content, structures containing, and elements, suitable for building RSS readers or data processing tools.

RSS and XML: The Cornerstone of Web SyndicationRSS and XML: The Cornerstone of Web SyndicationApr 29, 2025 am 12:22 AM

RSS and XML are the core technologies in network content distribution and data exchange. RSS is used to publish frequently updated content, and XML is used to store and transfer data. Development efficiency and performance can be improved through usage examples and best practices in real projects.

RSS Feeds: Exploring XML's Role and PurposeRSS Feeds: Exploring XML's Role and PurposeApr 28, 2025 am 12:06 AM

XML's role in RSSFeed is to structure data, standardize and provide scalability. 1.XML makes RSSFeed data structured, making it easy to parse and process. 2.XML provides a standardized way to define the format of RSSFeed. 3.XML scalability allows RSSFeed to add new tags and attributes as needed.

Scaling XML/RSS Processing: Performance Optimization TechniquesScaling XML/RSS Processing: Performance Optimization TechniquesApr 27, 2025 am 12:28 AM

When processing XML and RSS data, you can optimize performance through the following steps: 1) Use efficient parsers such as lxml to improve parsing speed; 2) Use SAX parsers to reduce memory usage; 3) Use XPath expressions to improve data extraction efficiency; 4) implement multi-process parallel processing to improve processing speed.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool