首页 > 代码库 > java 解析 xml 文件

java 解析 xml 文件

  学习下解析 xml 文件,这里用到了 org.dom4j 这个 jar 包,使用 eclipse 没有这个包的小伙伴可以去下个 jar 包,然后复制到项目路径下,右键 jar 包后 build path,add build path 即可。

  来引入相关依赖:

import java.io.File;
import java.util.List;

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

  注意会抛错,这里 throws 一下:

public static void main (String[] args) throws Exception{

}

  初始化变量:

SAXReader reader = new SAXReader();
File file = new File("***.xml");
Document document = reader.read(file);
Element root = document.getRootElement();
List<Element> childElements = root.elements();

  循环进行打印:

for (Element child : childElements) {
    List<Attribute> attributeList = child.attributes();
    for(Attribute attr : attributeList) {
        System.out.println(attr.getName() + ": " + attr.getValue());
    }
    List<Element> elementList = child.elements();
    for (Element ele : elementList) {
        System.out.println(ele.getName() + ": " + ele.getText());
    }
}

  还是很 easy 的嗷~

  xml文件中结构类似这样:

<?xml version="1.0" encoding="UTF-8"?> 
<books> 
   <book id="001"> 
      <title>Harry Potter</title> 
      <author>J K. Rowling</author> 
   </book> 
   <book id="002"> 
      <title>Learning XML</title> 
      <author>Erik T. Ray</author> 
   </book> 
</books> 

 

java 解析 xml 文件