Java 解析XML的几种方式:DOM、SAX、JDOM和DOM4J。
归纳总结Java解析XML主要有四中方式,分别是DOM、SAX、JDOM和DOM4J。其中DOM和SAX是官方包自带,另外两个JDOM和DOM4J是第三方包。
一、此篇测试代码用到的XML情况 。
1、XML内容展示
1 <?xml version="1.0" encoding="UTF-8"?> 2 <class> 3 <people> 4 <name>Jack</name> 5 <age>19</age> 6 <sex>male</sex> 7 <job>student</job> 8 </people> 9 <people> 10 <name>Merry</name> 11 <age>26</age> 12 <sex>female</sex> 13 <job>teacher</job> 14 </people> 15 </class>
2、所在项目位置
二、几种方式
1、DOM方式
代码及运行结果,已省略类名及main函数代码。
1 import org.w3c.dom.Document; 2 import org.w3c.dom.Element; 3 import org.w3c.dom.Node; 4 import org.w3c.dom.NodeList; 5 import org.xml.sax.SAXException; 6 import javax.xml.parsers.DocumentBuilder; 7 import javax.xml.parsers.DocumentBuilderFactory; 8 import javax.xml.parsers.ParserConfigurationException; 9 import java.io.File; 10 import java.io.IOException; 11 /** 12 * Create by 摩诘 on 2020/4/5 02:00 13 */ 14 try { 15 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 16 DocumentBuilder builder = factory.newDocumentBuilder(); 17 String path = HelloWorld.class.getClassLoader().getResource("config/peoples.xml").getPath(); 18 File file = new File(path); 19 Document document = builder.parse(file); 20 // 获取节点People集合 21 NodeList nodeList = document.getElementsByTagName("people"); 22 for (int i = 0; i < nodeList.getLength(); i++) { 23 // Element element=(Element) nodeList.item(i); 24 // NodeList childNodes=element.getChildNodes(); 25 Node node = nodeList.item(i); 26 NodeList childNodes = node.getChildNodes(); 27 for (int j = 0; j < childNodes.getLength(); j++) { 28 Node childNode = childNodes.item(j); 29 if (childNode.getNodeType() == Node.ELEMENT_NODE) { 30 // 获取节点名称 31 // 获取对应节点包含的值 32 System.out.println(childNode.getNodeName() + ":" + childNode.getFirstChild().getNodeValue()); 33 } 34 } 35 System.out.println("************************"); 36 } 37 } catch (ParserConfigurationException ex) { 38 //ex.printStackTrace(); 39 System.out.println("Error : " + ex.toString()); 40 } catch (IOException ex) { 41 //ex.printStackTrace(); 42 System.out.println("Error : " + ex.toString()); 43 } catch (SAXException ex) { 44 //ex.printStackTrace(); 45 System.out.println("Error : " + ex.toString()); 46 }
2、SAX方式
运行效率和内存使用方面最优的是SAX,但是由于SAX是基于事件的方式,所以SAX无法在编写XML的过程中对已编写内容进行修改,但对于不用进行频繁修改的需求,还是应该选择使用SAX。测试代码主要使用到两个类,一个主函数类HelloWorld,一个SAXHandler继承DefaultHandler并重写方法。
1 import org.xml.sax.helpers.DefaultHandler; 2 import javax.xml.parsers.SAXParser; 3 import javax.xml.parsers.SAXParserFactory; 4 /** 5 * Create by 摩诘 on 2020/4/5 17:30 6 */ 7 public class HelloWorld { 8 public static void main(String[] args) throws Exception{ 9 SAXParserFactory factory=SAXParserFactory.newInstance(); 10 SAXParser saxParser=factory.newSAXParser(); 11 DefaultHandler handel=new SAXHandler(); 12 saxParser.parse("src/config/peoples.xml",handel); 13 } 14 }
1 import org.xml.sax.Attributes; 2 import org.xml.sax.SAXException; 3 import org.xml.sax.helpers.DefaultHandler; 4 /** 5 * Create by 摩诘 on 2020/4/5 17:30 6 */ 7 public class SAXHandler extends DefaultHandler { 8 @Override 9 public void startDocument() throws SAXException { 10 super.startDocument(); 11 System.out.println("XML解析开始"); 12 } 13 14 @Override 15 public void endDocument() throws SAXException { 16 super.endDocument(); 17 System.out.println("XML解析结束"); 18 } 19 20 @Override 21 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { 22 super.startElement(uri, localName, qName, attributes); 23 if(qName.equals("people")){ 24 System.out.println("*************开始遍历poople*************"); 25 }else if(!qName.equals("people")&&!qName.equals("class")){ 26 System.out.println("节点名称:"+qName); 27 } 28 } 29 30 @Override 31 public void endElement(String uri, String localName, String qName) throws SAXException { 32 super.endElement(uri, localName, qName); 33 if(qName.equals("people")){ 34 System.out.println(qName+"遍历结束"); 35 System.out.println("************结束遍历people**************"); 36 } 37 } 38 39 @Override 40 public void characters(char[] ch, int start, int length) throws SAXException { 41 super.characters(ch, start, length); 42 String value=new String(ch,start,length).trim(); 43 if(!value.equals("")){ 44 System.out.println(value); 45 } 46 } 47 }
3、JDOM方式
这种方式为三方包,包地址:https://mvnrepository.com/search?q=jdom,通过构建maven项目引用,maven安装与配置:https://blog.csdn.net/github_37759996/article/details/90748461,创建maven Java程序:https://blog.csdn.net/YF_Li123/article/details/79953731?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1,上代码。
1 import org.jdom2.Document; 2 import org.jdom2.Element; 3 import org.jdom2.input.SAXBuilder; 4 import org.jdom2.JDOMException; 5 import java.io.*; 6 import java.util.List; 7 8 /** 9 * Create by 摩诘 on 2020/5/2 21:38 10 */ 11 public class HelloWorld { 12 public static void main(String[] args) { 13 SAXBuilder saxBuilder=new SAXBuilder(); 14 InputStream in; 15 try{ 16 in=new FileInputStream(new File("src\\config\\peoples.xml")); 17 Document document=saxBuilder.build(in); 18 Element rootElement=document.getRootElement(); 19 List<Element> peopleList=rootElement.getChildren(); 20 for (Element people:peopleList){ 21 List<Element> childernList=people.getChildren(); 22 for (Element childern:childernList){ 23 System.out.println("2"); 24 System.out.println(childern.getName()+":"+childern.getValue()); 25 } 26 } 27 }catch(FileNotFoundException e){ 28 e.printStackTrace(); 29 }catch(JDOMException e){ 30 e.printStackTrace(); 31 }catch(IOException e){ 32 e.printStackTrace(); 33 } 34 } 35 }
4、DOM4J
三方包,引用方式与JDOM方式类似。看代码
1 import org.dom4j.Attribute; 2 import org.dom4j.Document; 3 import org.dom4j.Element; 4 import org.dom4j.io.SAXReader; 5 import java.io.File; 6 import java.util.Iterator; 7 import java.util.List; 8 /** 9 * Create by 摩诘 on 2020/5/2 22:07 10 */ 11 public class HelloWorld { 12 public static void main(String[] args) { 13 SAXReader reader = new SAXReader(); 14 try{ 15 Document document = reader.read(new File("src/config/peoples.xml")); 16 Element rootElement = document.getRootElement(); 17 Iterator iterator = rootElement.elementIterator(); 18 while (iterator.hasNext()){ 19 Element stu = (Element) iterator.next(); 20 List<Attribute> attributes = stu.attributes(); 21 System.out.println("======获取属性值======"); 22 for (Attribute attribute : attributes) { 23 System.out.println(attribute.getValue()); 24 } 25 System.out.println("======遍历子节点======"); 26 Iterator iterator1 = stu.elementIterator(); 27 while (iterator1.hasNext()){ 28 Element stuChild = (Element) iterator1.next(); 29 System.out.println("节点名:"+stuChild.getName()+"---节点值:"+stuChild.getStringValue()); 30 } 31 } 32 }catch (Exception e){ 33 e.printStackTrace(); 34 } 35 } 36 }
三、整理参考了以下链接文章
https://www.jb51.net/article/115316.htm
https://blog.csdn.net/m0_37499059/article/details/80505567