JAVA读取XML文件并解析获取元素、属性值、子元素信息

关键字

  XML读取  InputStream   DocumentBuilderFactory   Element     Node

前言

  最近在学习Spring源码时,碰到读取XML配置文件的方法,整理下,备忘并和大家分享

正文(直接上源码)

XML文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans">
  3.  
  4. <bean name="HelloWorld" class="com.huishe.HelloWord">
  5. <property name="textone" value="Hello World!"></property>
  6. <property name="texttwo" value="Hello SUN!"></property>
  7. </bean>
  8.  
  9. </beans>

XMLParse解析源码

  1. package com.huishe.testOfSpring;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.InputStream;
  5.  
  6. import javax.xml.parsers.DocumentBuilder;
  7. import javax.xml.parsers.DocumentBuilderFactory;
  8.  
  9. import org.w3c.dom.Document;
  10. import org.w3c.dom.Element;
  11. import org.w3c.dom.Node;
  12. import org.w3c.dom.NodeList;
  13.  
  14. public class XMLParse {
  15.  
  16. public static void main(String[] args) throws Exception {
  17. //1-获取XML-IO流
  18. InputStream xmlInputStream = getXmlInputStream("xml/tinyioc.xml");
  19. //2-解析XML-IO流 ,获取Document 对象,以及Document对象 的根节点
  20. Element rootElement = getRootElementFromIs(xmlInputStream);
  21. //3~5-从根元素解析得到元素
  22. parseElementFromRoot(rootElement);
  23.  
  24.     //控制台输出:
        //name == HelloWorld
        //className == com.huishe.HelloWord
        //propertyEle: name == textone
        //propertyEle: value == Hello World!
        //propertyEle: name == texttwo
        //propertyEle: value == Hello SUN!
  25. }
  26.  
  27. //1-获取XML-IO流
  28. private static InputStream getXmlInputStream(String xmlPath){
  29. InputStream inputStream = null;
  30. try {
  31. //1-把要解析的 XML 文档转化为输入流,以便 DOM 解析器解析它
  32. inputStream= new FileInputStream(xmlPath);
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. }
  36. return inputStream;
  37. }
  38. //2-解析XML-IO流 ,获取Document 对象,以及Document对象 的根节点
  39. private static Element getRootElementFromIs(InputStream inputStream) throws Exception {
  40. if(inputStream == null){
  41. return null;
  42. }
  43. /*
  44. * javax.xml.parsers 包中的DocumentBuilderFactory用于创建DOM模式的解析器对象 ,
  45. * DocumentBuilderFactory是一个抽象工厂类,它不能直接实例化,但该类提供了一个newInstance方法 ,
  46. * 这个方法会根据本地平台默认安装的解析器,自动创建一个工厂的对象并返回。
  47. */
  48. //2-调用 DocumentBuilderFactory.newInstance() 方法得到创建 DOM 解析器的工厂
  49. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  50. //3-调用工厂对象的 newDocumentBuilder方法得到 DOM 解析器对象。
  51. DocumentBuilder docBuilder = factory.newDocumentBuilder();
  52. //4-调用 DOM 解析器对象的 parse() 方法解析 XML 文档,得到代表整个文档的 Document 对象,进行可以利用DOM特性对整个XML文档进行操作了。
  53. Document doc = docBuilder.parse(inputStream);
  54. //5-得到 XML 文档的根节点
  55. Element root =doc.getDocumentElement();
  56. //6-关闭流
  57. if(inputStream != null){
  58. inputStream.close();
  59. }
  60. return root;
  61. }
  62.  
  63. //3-从根元素解析得到元素
  64. private static void parseElementFromRoot(Element root) {
  65. NodeList nl = root.getChildNodes();
  66. for (int i = 0; i < nl.getLength(); i++) {
  67. Node node = nl.item(i);
  68. if (node instanceof Element) {
  69. Element ele = (Element) node;
  70. //4-从元素解析得到属性值
  71. getDataFromElement(ele);
  72. //5-从元素解析特定子元素并解析(以property为例)
  73. getCertainElementFromParentElement(ele);
  74. }
  75. }
  76. }
  77.  
  78. //4-从元素解析得到属性值
  79. private static void getDataFromElement(Element ele) {
  80. String name = ele.getAttribute("name");//根据属性名称读取属性值
  81. System.out.println("name == " + name);
  82. String className = ele.getAttribute("class");
  83. System.out.println("className == " + className);
  84. }
  85. //5-从元素解析特定子元素并解析(以property为例)
  86. private static void getCertainElementFromParentElement(Element ele) {
  87. NodeList propertyEleList = ele.getElementsByTagName("property");//根据标签名称获取标签元素列表
  88. for (int i = 0; i < propertyEleList.getLength(); i++) {
  89. Node node = propertyEleList.item(i);
  90. if (node instanceof Element) {
  91. Element propertyEle = (Element) node;
  92. String name = propertyEle.getAttribute("name");
  93. System.out.println("propertyEle: name == " + name);
  94. String value = propertyEle.getAttribute("value");
  95. System.out.println("propertyEle: value == " + value);
  96. }
  97. }
  98.  
  99. }
  100.  
  101. }
     
  1.  

总结

  读取XML配置涉及到IO、DocumentBuilderFactory、Node等概念,这里只使用,不具体分析

参考文献

1- https://blog.csdn.net/hua1017177499/article/details/78985166

JAVA读取XML文件并解析获取元素、属性值、子元素信息的更多相关文章

  1. java 读取XML文件作为配置文件

    首先,贴上自己的实例: XML文件:NewFile.xml(该文件与src目录同级) <?xml version="1.0" encoding="UTF-8&quo ...

  2. java读取xml文件报“org.xml.sax.SAXParseException: Premature end of file” .

    背景:java读取xml文件,xml文件内容只有“<?xml version="1.0" encoding="UTF-8"?>”一行 java读取该 ...

  3. java读取XML文件的四种方式

    java读取XML文件的四种方式 Xml代码 <?xml version="1.0" encoding="GB2312"?> <RESULT& ...

  4. java读取 xml文件

    java读取xml文件的四种方法  转自https://www.cnblogs.com/lingyao/p/5708929.html Xml代码 1 <?xml version="1. ...

  5. 通过Java读取xml文件内容

    读取XML中的内容就需要对XML进行解析,目前对XML进行解析的方法分为四种: 下面解析的方法是DOM4J,需要下载jar包dom4j:https://dom4j.github.io/ package ...

  6. 用java操作XML文件(DOM解析方式)

    XML 可扩展标记语言(Extensible Markup Language),是独立于软件和硬件的传输工具. XML的作用: (1)用作配置文件 (2)简化数据共享 (3)简化数据传输 XML DO ...

  7. JAVA读取XML文件数据

    XML文档内容如下: <?xml version="1.0" encoding="UTF-8"?> <root> <field t ...

  8. java读取XML文件,及封装XML字符串

    package com.yyl.text; import java.io.FileInputStream; import java.util.ArrayList; import org.junit.T ...

  9. 【Java】XML文件的解析

    import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import ja ...

随机推荐

  1. APP-1-相关介绍及资料

    一年前研究了下MUI框架,也做了一些简单的功能,将整个过程整理下.. 1.Hbuilder官网 http://www.dcloud.io/ 2.MUI前端框架 http://www.dcloud.io ...

  2. World Cup 996B(排队模拟)

    题意:有n个通道,按顺序每一次站一个通道,直到所站的通道没有人 分析:模拟这个过程 #include<cstdio> int main() { ]; while(~scanf(" ...

  3. 1.Python基础知识小结:

    Python3下载地址:https://www.python.org/downloads/windows/ python3 windows安装参考地址: https://jingyan.baidu.c ...

  4. Zabbix 3.0 LTS安装配置

    关于Zabbix监控项类型的官网介绍: https://www.zabbix.com/documentation/3.4/zh/manual/config/items/itemtypes zabbix ...

  5. NetStream 记录

    bufferLength : Number [只读] 数据当前存在于缓冲区中的秒数.(已进入缓冲区的秒数) bufferTime : Number 指定在开始显示流之前需要多长时间将消息存入缓冲区.( ...

  6. Spring事务异常rollback-only

    转自:https://blog.csdn.net/sgls652709/article/details/49472719 前言 在利用单元测试验证spring事务传播机制的时候出现了下面的异常: Tr ...

  7. String特殊值的判断方式

    对String的特殊值的判断上,除了要关注是否为null,还要关注是否是空字符串. 经常处理的时候直接判断是否为Null就好了,这样很容易出现问题: if(null!=str) { //not goo ...

  8. Zookeeper与HBse安装过程纪录

    1 zookeeper安装 1.1 环境变量 1.2 配置zoo.cfg 初次使用 ZooKeeper 时, 需要将 $ZOOKEEPER_HOME/conf 目录下的 zoo_sample.cfg ...

  9. C++学习一Virtual

    没有系统性学习C++,所以工作中使用特别别扭,也不是不会,也不是不懂,但读代码和写代码时总有点生疏感.所以该补还是补起来,现在想想还是学生时代学习的知识更加扎实,那是融入骨子里的. virtual函数 ...

  10. http://sourceforge.net/projects/rtspdirectshow/

    如何做一个解析rtsp协议的h264压缩的实时视频流播放器,带保存功能,目前我有rtsp协议的h264压缩后的实时视频流,目前想开发一个客户端,来播放该实时视频流,同时保存为视频文件,目前似乎有方案是 ...