XML 解析

本文介绍了XML在配置和数据交互中的作用,详细阐述了XML在Java中三种配置位置及其读取方式,特别是使用Properties类进行读取。此外,通过dom4j结合xpath深入解析XML文件,讲解了xpath的语法、Document和Node的概念以及如何获取元素和文本的值。

hello,大家好!我是求哥的马子!今天来给大家分享一篇关于xml 的文章

1.XML作用
   1.1配置 (保存数据)
   *.xml和*.properties INI   yml  springboot

   1.2数据交互(获取第三方数据)
    webservice   xml  ajax    json
   

2.Java中3种配置位置及读取方式
   2.1如何使用Properties读取配置文件
      1)*.properties文件以键值对的方式存储数据;

user=\u50BB\u9E1F\u5F6D\u6BC5 (键=值)
password=8888888


      2)使用Properties类读取配置文件;
       2.2 配置位置
      1)存放于根目录下,/代表获取src根目录的绝对路径
      2)存放于同一类的包下,不加/代表同类名包下的相对路径;
      3)存放于WEB-INF目录下
      ServletContext sc=this.getServletContext();
      InputStream is=sc.getResourceAsStream("/WEB-INF/db.properties");
日志 log for java

package test;

import java.io.InputStream;
import java.util.Properties;

public class Demo1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//获取读取文件的io流
		// 相对路径 同一路径下可用
		InputStream is = Demo1.class.getResourceAsStream("db.properties");
		//  绝对路径  
		InputStream is1 = Demo1.class.getResourceAsStream("/test/db.properties");

		
		System.out.println(is);
		//创建获取properties的工具类
		Properties pt = new Properties();
		try {
			pt.load(is);
			String name = pt.getProperty("user");
			String pwd = pt.getProperty("password");
			
			System.out.println(name+"= "+pwd);
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	}

}


3.dom4j+xpath解析xml文件  document   for  java   SAX   
    1)xpath类似数据库中的select语句;
    2)Document有节点(Node)组成:元素.节点、属性、文本等
    3)  Node(节点)  Element(元素) 区别  getText();
    3)selectNodes()获取节点下所有子节点;
    4)selectSingleNode()获取单个节点信息;
   
    

package test;

import java.io.InputStream;
import java.util.List;

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

public class Demo2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//获取读取文件的io流
		InputStream is = Demo2.class.getResourceAsStream("students.xml");
		
		System.out.println(is);
		//创建获取xml的工具类对象 SAXReader
		SAXReader sr = new SAXReader();
		//获取xml 配置文件
		try {
			//获取document 对象
			/*Document doc = sr.read(is);
			List selectNodes = doc.selectNodes("/students/student");
			System.out.println(selectNodes.size());
			 
			System.out.println("       --");
			
			List selectNodes1 = doc.selectNodes("/students/student/name");
			System.out.println(selectNodes1.size());
			*/		
			Document doc = sr.read(is);
			List<Node> selectNodes1 = doc.selectNodes("/students/student");
			for (Node node : selectNodes1) {
				/*System.out.println(node);*/
				//获取student 节点下的 name 节点
				Node nameNode = node.selectSingleNode("name");
				String name = nameNode.getText();
				System.out.println(name);
				
				//节点对象没有属性 获取属性 1.将node 装node 转化成元素element
				Element el = (Element) node;
				String sid = el.attributeValue("sid");
				System.out.println(sid);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}

5) xpath语法:/(定位路径)、@(获取属性)

<?xml version="1.0" encoding="UTF-8"?>
<students>
	<student zid="sz001">
		<name>小明</name>
	</student>
	<student zid="sz002">
		<name>小芳</name>
	</student>
	<student zid='u003s'>
		<name>小王</name>
	</student>
	<student zid='w004' qq="1111">
		<name>小李</name>
	</student>
</students>
package test;

import java.io.InputStream;
import java.util.List;

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

public class Demo3 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//获取读取文件的io流
		InputStream is = Demo3.class.getResourceAsStream("students.xml");
		
		SAXReader sr = new SAXReader();
		try {
			//绝对路径 / . 相对 // .. 
			Document doc = sr.read(is);
			/*List nodes = doc.selectNodes("//*");*/
/*			Node node = doc.selectSingleNode("students/student[@zid='s001']");
 * Node selectSingleNode = node.selectSingleNode("name");
			System.out.println(selectSingleNode.getText());
*/
			//Node node = doc.selectSingleNode("students/student[@qq]");
			 //List<Node> selectNodes = doc.selectNodes("//*[starts-with(@zid,'s')]");头
			//List<Node> selectNodes = doc.selectNodes("//*[ends-with(@zid,'s')]");尾
			List<Node> selectNodes = doc.selectNodes("//*[contains(@zid,'s')]");//包含
			for (Node node : selectNodes) {
				Node selectSingleNode = node.selectSingleNode("name");
				System.out.println(selectSingleNode.getText());
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	
	}
}

3.3获取元素的值

config.xml代码

<?xml version="1.0" encoding="UTF-8"?>
	<!--
		config标签:可以包含0~N个action标签
	-->
<config>
	<!--
		action标签:可以饱含0~N个forward标签
		path:以/开头的字符串,并且值必须唯一 非空
		type:字符串,非空
	-->
	<action path="/regAction" type="test.RegAction">
		<!--
			forward标签:没有子标签; 
			name:字符串,同一action标签下的forward标签name值不能相同 ;
			path:以/开头的字符串
			redirect:只能是false|true,允许空,默认值为false
		-->
		<forward name="failed" path="/reg.jsp" redirect="false" />
		<forward name="success" path="/login.jsp" redirect="true" />
	</action>

	<action path="/loginAction" type="test.LoginAction">
		<forward name="failed" path="/login.jsp" redirect="false" />
		<forward name="success" path="/main.jsp" redirect="true" />
	</action>
</config>

config.xml 解析

package test;

import java.io.InputStream;
import java.util.List;

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

public class Z1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		InputStream is = Z1.class.getResourceAsStream("config.xml");
		SAXReader sr = new SAXReader();
		try {
			Document doc = sr.read(is);
			List<Node> selectNodes2 = doc.selectNodes("/config/action");
			List<Node> selectNodes = doc.selectNodes("/config/action/forward");
			for (Node node : selectNodes) {
				//Node selectSingleNode = node.selectSingleNode("forward");
			//	Node path = node.selectSingleNode("path");

				//String text = selectSingleNode.getText();
				//System.out.println(text);
				
				Element el = (Element) node;
				String path = el.attributeValue("path");
				String redirect = el.attributeValue("redirect");
				String name = el.attributeValue("name");
				System.out.println(path+" ------"+name+"  "+redirect);
			}
			for (Node node : selectNodes2) {
				Element el = (Element) node;
				String a1 = el.attributeValue("path");
				String a2 = el.attributeValue("type");

				System.out.println(a1+"path type "+a2);
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	
	
	
	}

}


运行结果

/reg.jsp ------failed  false
/login.jsp ------success  true
/login.jsp ------failed  false
/main.jsp ------success  true
/regActionpath type test.RegAction
/loginActionpath type test.LoginAction

3.4获取元素/文本的值

hibernate.cfg.xml 代码

<?xml version="1.0" encoding="UTF-8"?>

<hibernate-configuration>
	<session-factory>
		<!-- 1.数据库相关 -->
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/t207?useUnicode=true&amp;characterEncoding=UTF-8</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- 2.调试相关 -->
		<property name="show_sql">true</property>
		<property name="format_sql">true</property>

		<!-- 开启二级缓存 -->
		<property name="hibernate.cache.use_second_level_cache">true</property>
		<!-- 开启查询缓存 -->
		<property name="hibernate.cache.use_query_cache">true</property>
		<!-- EhCache驱动 -->
		<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
		<!-- 3.实体类映射文件 -->
		<!-- <mapping resource="entity/user.hbm.xml"/> -->
		<mapping resource="entity/worker.hbm.xml" />
		<mapping resource="entity/student.hbm.xml" />
		<mapping resource="entity/user.hbm.xml" />
		<mapping resource="entity/order.hbm.xml" />
		<mapping resource="entity/orderItem.hbm.xml" />
		<mapping resource="entity/treeNode.hbm.xml" />
		<mapping resource="entity/book.hbm.xml" />
		<mapping resource="entity/category.hbm.xml" />




	</session-factory>





</hibernate-configuration>	

xml 解析

package test;

import java.io.InputStream;
import java.util.List;

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

public class Z2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		InputStream is = Z2.class.getResourceAsStream("hibernate.cfg.xml");
		SAXReader sr = new SAXReader();
		Document doc =null;
		try {
			 doc = sr.read(is);
			
			//List<Node> selectNodes = doc.selectNodes("//*");
 List<Node> selectNodes2 = doc.selectNodes("/hibernate-configuration/session-factory/mapping");

             List<Node> selectNodes = doc.selectNodes("/hibernate-configuration/session-factory/property");
			for (Node node : selectNodes) {
				
				System.out.println(node.getText());
				/*String path = el.attributeValue("path");
				String redirect = el.attributeValue("redirect");*/
				Element el = (Element) node;
				String name = el.attributeValue("name");
				System.out.println(" ------"+name+"-----");
			}
			System.out.println("---------");
			for (Node node : selectNodes2) {
				Element el = (Element) node;
				String resource = el.attributeValue("resource");
				System.out.println(resource);
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		
	}
	
	

}
root
 ------connection.username-----
root
 ------connection.password-----
jdbc:mysql://localhost:3306/t207?useUnicode=true&characterEncoding=UTF-8
 ------connection.url-----
com.mysql.jdbc.Driver
 ------connection.driver_class-----
org.hibernate.dialect.MySQLDialect
 ------dialect-----
true
 ------show_sql-----
true
 ------format_sql-----
true
 ------hibernate.cache.use_second_level_cache-----
true
 ------hibernate.cache.use_query_cache-----
org.hibernate.cache.ehcache.EhCacheRegionFactory
 ------hibernate.cache.region.factory_class-----
---------
entity/worker.hbm.xml
entity/student.hbm.xml
entity/user.hbm.xml
entity/order.hbm.xml
entity/orderItem.hbm.xml
entity/treeNode.hbm.xml
entity/book.hbm.xml
entity/category.hbm.xml

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值