归纳总结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 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方式
// TODO
三、整理参考了以下链接文章
https://www.jb51.net/article/115316.htm
https://blog.csdn.net/m0_37499059/article/details/80505567
来源:https://www.cnblogs.com/mojiejushi/p/12635674.html