Parsing process of reading XML file content through Java

This article mainly introduces the content parsing process of reading XML files through Java. It is introduced in great detail through the example code, which has a certain reference value for everyone's study or work. Friends in need can refer to it

You need to download the jar package Dom4j: https://dom4j.github.io/

package com.zyb.xml;

import java.io.File;
import java.util.Iterator;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class testXml {

  public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    //1.创建SAXReader对象用于读取xml文件
    SAXReader reader = new SAXReader();
    //2.读取xml文件,获得Document对象
    Document doc = reader.read(new File("src/book.xml"));
    //3.获取根元素
    Element root = doc.getRootElement();
    //4.获取根元素下的所有子元素(通过迭代器)
    Iterator<Element> it = root.elementIterator();
    while(it.hasNext()){

      Element e = it.next();
      //获取id属性(attribute是属性的意思)
      Attribute id = e.attribute("id");
      System.out.println(id.getName()+" = "+id.getStringValue());
      Element author = e.element("author");
      Element money = e.element("price");
      Element time = e.element("time");
      System.out.println(author.getName()+" = "+author.getStringValue());
      System.out.println(money.getName()+" = "+money.getData());
      System.out.println(time.getName()+" = "+time.getText());
      System.out.println("---------------------------------------------------------------");
    }
  }

}

Operation results:

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>