Java中的XML读取
2017-03-06 20:25
267 查看
XML的作用
-不同软件间的数据传输-不同系统间的数据传输
-不同平台间的数据共享
XML四种解析方式
-DOM解析-SAX解析
-DOM4J解析
-JDOM解析
-DOM解析与SAX解析不需要额外的jar,是Java官方的解析方式。
-解析遇到乱码时可以修改xml中编码方式,或者对InputStream流进行InputStreamReader包装并指定编码方式。
常用XML节点类型
节点类型 | NodeType | Named Constant | nodeName 的返回值 | nodeValue的返回值 |
---|---|---|---|---|
Element | 1 | ELEMENT_NODE | element name | null |
Attr | 2 | ATTRIBUTE_NODE | 属性名称 | 属性值 |
Text | 3 | TEXT_NODE | text | 节点内容 |
DOM解析
-将整个xml加载到内存中再解析-所解析的XML文件(以后的解析方法中不再赘述)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"> <!-- 引入外部属性文件 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置c3p0连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClass}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 配置hibernate其他相关属性 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!-- 注入连接池 --> <property name="dataSource" ref="dataSource"/> <!-- 配置hibernate属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <!-- 加载hibernate配置文件 --> <property name="mappingResources"> <list> <value>entity/Employee.hbm.xml</value> <value>entity/Department.hbm.xml</value> </list> </property> </bean> <!-- 配置Action --> <bean id="employeeAction" class="action.EmployeeAciton" scope="prototype"> <property name="employeeService" ref="employeeService"/> <property name="departmentService" ref="departmentService"/> </bean> <bean id="departmentAction" class="action.DepartmentAction" scope="prototype"> <property name="departmentService" ref="departmentService"/> </bean> <!-- 配置业务层 --> <bean id="employeeService" class="service.EmployeeServiceImpl"> <property name="employeeDAO" ref="employeeDAO"/> </bean> <bean id="departmentService" class="service.DepartmentServiceImpl"> <property name="departmentDAO" ref="departmentDAO"/> </bean> <!-- 配置DAO --> <bean id="employeeDAO" class="dao.EmployeeDAOImpl"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="departmentDAO" class="dao.DepartmentDAOImpl"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 开启注解事务 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DOM {
public static void main(String[] args) { // 创建一个DocumentBuilderFactory对象 DocumentBuilderFactory xDocumentBuilderFactory = DocumentBuilderFactory.newInstance(); try { // 创建一个DocumentBuilder对象 DocumentBuilder xdocumentBuilder = xDocumentBuilderFactory.newDocumentBuilder(); // 传入要解析的XML文件 Document xDocument = xdocumentBuilder.parse("applicationContext.xml"); // 通过标签获得节点集合 NodeList beanList = xDocument.getElementsByTagName("bean"); System.out.println("共有" + beanList.getLength() + "个节点"); // 遍历每一个bean节点 for (int i = 0; i < beanList.getLength(); i++) { // 获取其中一个节点 Node bean = beanList.item(i); // 获取所有属性值 NamedNodeMap attrs = bean.getAttributes(); System.out.println("第" + (i + 1) + "个bean有" + attrs.getLength() + "个属性"); // 遍历节点属性 for (int j = 0; j < attrs.getLength(); j++) { // 获取某一属性 Node attr = attrs.item(j); // 获取属性名 System.out.println("属性名:" + attr.getNodeName()); // 获取属性值 System.out.println("属性值:" + attr.getNodeValue()); } // 当不需要遍历所有属性时,采用以下方法可遍历个别已知属性 Element bean2 = (Element) beanList.item(i); System.out.println("采用Element方式获得id:" + bean2.getAttribute("id")); // 解析bean节点的子节点 NodeList childBean = bean.getChildNodes(); // 遍历 childBean每个节点的节点名和节点值,空白和换行符也会算作子节点 System.out.println("第" + (i + 1) + "bean" + "共有" + childBean.getLength() + "个子节点"); for (int j = 0; j < childBean.getLength(); j++) { // 区分text类型的Node以及element类型的Node,过滤掉空白与换行符 if (childBean.item(j).getNodeType() == Node.ELEMENT_NODE) { // 获取element类型节点的节点名 System.out.println("第" + (j + 1) + "个节点的节点名:" + childBean.item(j).getNodeName()); // element会把标签中的内容视为标签的子节点,所以要想获取内容需先访问子节点 if(childBean.item(j).getFirstChild() != null){ System.out.println("第" + (j + 1) + "个节点的节点值:" + childBean.item(j).getFirstChild().getNodeValue()); } // 获取子节点的节点值以及标签之间的值 System.out.println("第" + (j + 1) + "个节点的节点值:" + childBean.item(j).getTextContent()); } } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
}
-Java代码
import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class DOM { public static void main(String[] args) { // 创建一个DocumentBuilderFactory对象 DocumentBuilderFactory xDocumentBuilderFactory = DocumentBuilderFactory.newInstance(); try { // 创建一个DocumentBuilder对象 DocumentBuilder xdocumentBuilder = xDocumentBuilderFactory.newDocumentBuilder(); // 传入要解析的XML文件 Document xDocument = xdocumentBuilder.parse("applicationContext.xml"); // 通过标签获得节点集合 NodeList beanList = xDocument.getElementsByTagName("bean"); System.out.println("共有" + beanList.getLength() + "个节点"); // 遍历每一个bean节点 for (int i = 0; i < beanList.getLength(); i++) { // 获取其中一个节点 Node bean = beanList.item(i); // 获取所有属性值 NamedNodeMap attrs = bean.getAttributes(); System.out.println("第" + (i + 1) + "个bean有" + attrs.getLength() + "个属性"); // 遍历节点属性 for (int j = 0; j < attrs.getLength(); j++) { // 获取某一属性 Node attr = attrs.item(j); // 获取属性名 System.out< 14764 span class="hljs-preprocessor">.println("属性名:" + attr.getNodeName()); // 获取属性值 System.out.println("属性值:" + attr.getNodeValue()); } // 当不需要遍历所有属性时,采用以下方法可遍历个别已知属性 Element bean2 = (Element) beanList.item(i); System.out.println("采用Element方式获得id:" + bean2.getAttribute("id")); // 解析bean节点的子节点 NodeList childBean = bean.getChildNodes(); // 遍历 childBean每个节点的节点名和节点值,空白和换行符也会算作子节点 System.out.println("第" + (i + 1) + "bean" + "共有" + childBean.getLength() + "个子节点"); for (int j = 0; j < childBean.getLength(); j++) { // 区分text类型的Node以及element类型的Node,过滤掉空白与换行符 if (childBean.item(j).getNodeType() == Node.ELEMENT_NODE) { // 获取element类型节点的节点名 System.out.println("第" + (j + 1) + "个节点的节点名:" + childBean.item(j).getNodeName()); // element会把标签中的内容视为标签的子节点,所以要想获取内容需先访问子节点 if(childBean.item(j).getFirstChild() != null){ System.out.println("第" + (j + 1) + "个节点的节点值:" + childBean.item(j).getFirstChild().getNodeValue()); } // 获取子节点的节点值以及标签之间的值 System.out.println("第" + (j + 1) + "个节点的节点值:" + childBean.item(j).getTextContent()); } } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
共有9个节点
第1个bean有2个属性
属性名:class
属性值:com.mchange.v2.c3p0.ComboPooledDataSource
属性名:id
属性值:dataSource
采用Element方式获得id:dataSource
第1bean共有9个子节点
第2个节点的节点名:property
第2个节点的节点值:
第4个节点的节点名:property
第4个节点的节点值:
第6个节点的节点名:property
第6个节点的节点值:
第8个节点的节点名:property
第8个节点的节点值:
第2个bean有2个属性
属性名:class
属性值:org.springframework.orm.hibernate4.LocalSessionFactoryBean
属性名:id
属性值:sessionFactory
采用Element方式获得id:sessionFactory
第2bean共有13个子节点
第4个节点的节点名:property
第4个节点的节点值:
第8个节点的节点名:property
第8个节点的节点值:
第8个节点的节点值:
org.hibernate.dialect.MySQLDialect true true update
第12个节点的节点名:property
第12个节点的节点值:
第12个节点的节点值:
entity/Employee.hbm.xml entity/Department.hbm.xml
第3个bean有3个属性
属性名:class
属性值:action.EmployeeAciton
属性名:id
属性值:employeeAction
属性名:scope
属性值:prototype
采用Element方式获得id:employeeAction
第3bean共有5个子节点
第2个节点的节点名:property
第2个节点的节点值:
第4个节点的节点名:property
第4个节点的节点值:
第4个bean有3个属性
属性名:class
属性值:action.DepartmentAction
属性名:id
属性值:departmentAction
属性名:scope
属性值:prototype
采用Element方式获得id:departmentAction
第4bean共有3个子节点
第2个节点的节点名:property
第2个节点的节点值:
第5个bean有2个属性
属性名:class
属性值:service.EmployeeServiceImpl
属性名:id
属性值:employeeService
采用Element方式获得id:employeeService
第5bean共有3个子节点
第2个节点的节点名:property
第2个节点的节点值:
第6个bean有2个属性
属性名:class
属性值:service.DepartmentServiceImpl
属性名:id
属性值:departmentService
采用Element方式获得id:departmentService
第6bean共有3个子节点
第2个节点的节点名:property
第2个节点的节点值:
第7个bean有2个属性
属性名:class
属性值:dao.EmployeeDAOImpl
属性名:id
属性值:employeeDAO
采用Element方式获得id:employeeDAO
第7bean共有3个子节点
第2个节点的节点名:property
第2个节点的节点值:
第8个bean有2个属性
属性名:class
属性值:dao.DepartmentDAOImpl
属性名:id
属性值:departmentDAO
采用Element方式获得id:departmentDAO
第8bean共有3个子节点
第2个节点的节点名:property
第2个节点的节点值:
第9个bean有2个属性
属性名:class
属性值:org.springframework.orm.hibernate4.HibernateTransactionManager
属性名:id
属性值:transactionManager
采用Element方式获得id:transactionManager
第9bean共有3个子节点
第2个节点的节点名:property
第2个节点的节点值:
SAX解析
-通过自己创建的Handler处理类去逐个分析遇到的节点-startElement解析开始节点
-endElement解析结束节点
主函数
import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import entity.Bean; import handler.SAXParserHandler; public class SAX { public static void main(String[] args) { // 获取一个SAXParseFactory的实例 SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); try { // 通过saxParserFactory获取SAXparse SAXParser saxParser = saxParserFactory.newSAXParser(); // 创建handler对象 SAXParserHandler saxParserHandler = new SAXParserHandler(); saxParser.parse("applicationContext.xml", saxParserHandler); System.out.println("bean个数:"+saxParserHandler.getBeanList().size()); for (Bean bean : saxParserHandler.getBeanList()) { System.out.println(bean.getId()); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
处理类
import java.util.ArrayList; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import entity.Bean; public class SAXParserHandler extends DefaultHandler { // 通过该全局变量确定已遍历的bean的数目 private int beanIndex = 0; // 用于存放属性值 private String value = null; // 创建一个bean对象 private Bean bean; // 用于保存遍历过的bean private ArrayList<Bean> beanList = new ArrayList<Bean>(); // 用来解析xml文件的开始标签 @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { super.startElement(uri, localName, qName, attributes); // 开始解析bean元素属性 if (qName.equals("bean")) { // 创建一个bean对象 bean = new Bean(); // 遍历一个bean,则beanIndex+1; beanIndex++; // 获取属性的个数 int num = attributes.getLength(); for (int i = 0; i < num; i++) { System.out.println("bean" + "第" + (i + 1) + "个属性名" + attributes.getQName(i)); System.out.println("属性值:" + attributes.getValue(i)); if (attributes.getQName(i).equals("id")) { bean.setId(attributes.getValue(i)); } } } else { System.out.println("节点名是:" + qName); } } // 用来遍历xml的结束标签 @Override public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); if (qName.equals("bean")) { beanList.add(bean); bean = null; System.out.println("第" + beanIndex + "个bean结束遍历"); } else if (qName.equals("class")) { bean.setClazz(value); } else if (qName.equals("scope")) { bean.setScope(value); } } // 标识解析开始 @Override public void startDocument() throws SAXException { super.startDocument(); System.out.println("SAX解析开始"); } // 标识解析结束 @Override public void endDocument() throws SAXException { super.endDocument(); System.out.println("SAX解析结束"); } // 获得节点值 @Override public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); // 获得节点值 value = new String(ch, start, length); // 判断节点值是否为空 if (!value.trim().equals("")) { System.out.println("节点值:" + value); } } public ArrayList<Bean> getBeanList() { return beanList; } }
实体类
public class Bean { private String id; private String clazz; private String scope; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getClazz() { return clazz; } public void setClazz(String clazz) { this.clazz = clazz; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } }
输出结果
SAX解析开始节点名是:beans
节点名是:context:property-placeholder
bean第1个属性名id
属性值:dataSource
bean第2个属性名class
属性值:com.mchange.v2.c3p0.ComboPooledDataSource
节点名是:property
节点名是:property
节点名是:property
节点名是:property
第1个bean结束遍历
bean第1个属性名id
属性值:sessionFactory
bean第2个属性名class
属性值:org.springframework.orm.hibernate4.LocalSessionFactoryBean
节点名是:property
节点名是:property
节点名是:props
节点名是:prop
节点值:org.hibernate.dialect.MySQLDialect
节点名是:prop
节点值:true
节点名是:prop
节点值:true
节点名是:prop
节点值:update
节点名是:property
节点名是:list
节点名是:value
节点值:entity/Employee.hbm.xml
节点名是:value
节点值:entity/Department.hbm.xml
第2个bean结束遍历
bean第1个属性名id
属性值:employeeAction
bean第2个属性名class
属性值:action.EmployeeAciton
bean第3个属性名scope
属性值:prototype
节点名是:property
节点名是:property
第3个bean结束遍历
bean第1个属性名id
属性值:departmentAction
bean第2个属性名class
属性值:action.DepartmentAction
bean第3个属性名scope
属性值:prototype
节点名是:property
第4个bean结束遍历
bean第1个属性名id
属性值:employeeService
bean第2个属性名class
属性值:service.EmployeeServiceImpl
节点名是:property
第5个bean结束遍历
bean第1个属性名id
属性值:departmentService
bean第2个属性名class
属性值:service.DepartmentServiceImpl
节点名是:property
第6个bean结束遍历
bean第1个属性名id
属性值:employeeDAO
bean第2个属性名class
属性值:dao.EmployeeDAOImpl
节点名是:property
第7个bean结束遍历
bean第1个属性名id
属性值:departmentDAO
bean第2个属性名class
属性值:dao.DepartmentDAOImpl
节点名是:property
第8个bean结束遍历
bean第1个属性名id
属性值:transactionManager
bean第2个属性名class
属性值:org.springframework.orm.hibernate4.HibernateTransactionManager
节点名是:property
第9个bean结束遍历
节点名是:tx:annotation-driven
SAX解析结束
bean个数:9
dataSource
sessionFactory
employeeAction
departmentAction
employeeService
departmentService
employeeDAO
departmentDAO
transactionManager
JDOM解析
-需要jdom-2.0.6.jar主类
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import entity.Bean; public class JDOM { private static Bean beanEntity; private static ArrayList<Bean> beanList = new ArrayList<Bean>(); public static void main(String[] args) { // 创建SAXBuilder SAXBuilder saxBuilder = new SAXBuilder(); try { // 创建输入流,将xml加载到输入流中 InputStream inputStream = new FileInputStream("applicationContext.xml"); // 指定编码方式,防止中文乱码 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); // 将输入流加载到saxBuilder中 Document document = saxBuilder.build(inputStreamReader); // 获取根节点 Element rootElement = document.getRootElement(); // 获取子节点集合 List<Element> listElemrnt = rootElement.getChildren(); // 遍历子节点集合 for (Element bean : listElemrnt) { // 创建bean对象 beanEntity = new Bean(); System.out.println("开始解析第" + (listElemrnt.indexOf(bean) + 1) + "bean"); // 解析bean属性 List<Attribute> attrlist = bean.getAttributes(); // 获取特定属性值 // System.out.println(bean.getAttributeValue("id")); for (Attribute attribute : attrlist) { // 获得节点名称 System.out.println("属性名:" + attribute.getName()); // 保存有意义的文本,自动过滤空格回车 System.out.println("属性值:" + attribute.getValue()); if (attribute.getName().equals("id")) { beanEntity.setId(attribute.getValue()); } } // 对bean节点子孙节点及节点值进行遍历 List<Element> beanChildren = bean.getChildren(); for (Element child : beanChildren) { // 获得节点名称 System.out.println("节点名:" + child.getName()); // 保存有意义的文本,自动过滤空格回车 System.out.println("节点值:" + child.getValue()); if (child.getName().equals("property")) { beanEntity.setClazz(child.getValue()); } } beanList.add(beanEntity); beanEntity = null; System.out.println("集合长度:"+beanList.size()); for (Bean beanElement : beanList) { System.out.println(beanElement.getId()); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
输出结果
开始解析第1bean属性名:location
属性值:classpath:jdbc.properties
集合长度:1
null
开始解析第2bean
属性名:id
属性值:dataSource
属性名:class
属性值:com.mchange.v2.c3p0.ComboPooledDataSource
节点名:property
节点值:
节点名:property
节点值:
节点名:property
节点值:
节点名:property
节点值:
集合长度:2
null
dataSource
开始解析第3bean
属性名:id
属性值:sessionFactory
属性名:class
属性值:org.springframework.orm.hibernate4.LocalSessionFactoryBean
节点名:property
节点值:
节点名:property
节点值:
org.hibernate.dialect.MySQLDialect true true update
节点名:property
节点值:
entity/Employee.hbm.xml entity/Department.hbm.xml
集合长度:3
null
dataSource
sessionFactory
开始解析第4bean
属性名:id
属性值:employeeAction
属性名:class
属性值:action.EmployeeAciton
属性名:scope
属性值:prototype
节点名:property
节点值:
节点名:property
节点值:
集合长度:4
null
dataSource
sessionFactory
employeeAction
开始解析第5bean
属性名:id
属性值:departmentAction
属性名:class
属性值:action.DepartmentAction
属性名:scope
属性值:prototype
节点名:property
节点值:
集合长度:5
null
dataSource
sessionFactory
employeeAction
departmentAction
开始解析第6bean
属性名:id
属性值:employeeService
属性名:class
属性值:service.EmployeeServiceImpl
节点名:property
节点值:
集合长度:6
null
dataSource
sessionFactory
employeeAction
departmentAction
employeeService
开始解析第7bean
属性名:id
属性值:departmentService
属性名:class
属性值:service.DepartmentServiceImpl
节点名:property
节点值:
集合长度:7
null
dataSource
sessionFactory
employeeAction
departmentAction
employeeService
departmentService
开始解析第8bean
属性名:id
属性值:employeeDAO
属性名:class
属性值:dao.EmployeeDAOImpl
节点名:property
节点值:
集合长度:8
null
dataSource
sessionFactory
employeeAction
departmentAction
employeeService
departmentService
employeeDAO
开始解析第9bean
属性名:id
属性值:departmentDAO
属性名:class
属性值:dao.DepartmentDAOImpl
节点名:property
节点值:
集合长度:9
null
dataSource
sessionFactory
employeeAction
departmentAction
employeeService
departmentService
employeeDAO
departmentDAO
开始解析第10bean
属性名:id
属性值:transactionManager
属性名:class
属性值:org.springframework.orm.hibernate4.HibernateTransactionManager
节点名:property
节点值:
集合长度:10
null
dataSource
sessionFactory
employeeAction
departmentAction
employeeService
departmentService
employeeDAO
departmentDAO
transactionManager
开始解析第11bean
属性名:transaction-manager
属性值:transactionManager
集合长度:11
null
dataSource
sessionFactory
employeeAction
departmentAction
employeeService
departmentService
employeeDAO
departmentDAO
transactionManager
null
DOM4J解析
主类
import java.io.File; import java.util.Iterator; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class DOM4J { public static void main(String[] args) { SAXReader saxReader = new SAXReader(); try { // 通过saxReader加载xml文件并获取document对象 Document document = saxReader.read(new File("applicationContext.xml")); Element beans = document.getRootElement(); Iterator<Element> iterator = beans.elementIterator(); while (iterator.hasNext()) { Element bean = iterator.next(); System.out.println("开始遍历:"+bean.getName()); // 获取bean的属性名以及属性值 List<Attribute> beanList = bean.attributes(); for (Attribute attribute : beanList) { System.out.println("节点名:" + attribute.getName()); System.out.println("节点值:" + attribute.getValue()); } Iterator<Element> beanIt = bean.elementIterator(); while (beanIt.hasNext()) { Element beanChild = beanIt.next(); System.out.println("子节点名:" + beanChild.getName()); System.out.println("子节点值:" + beanChild.getStringValue()); } } } catch (DocumentException e) { e.printStackTrace(); } } }
输出结果
开始遍历:property-placeholder节点名:location
节点值:classpath:jdbc.properties
开始遍历:bean
节点名:id
节点值:dataSource
节点名:class
节点值:com.mchange.v2.c3p0.ComboPooledDataSource
子节点名:property
子节点值:
子节点名:property
子节点值:
子节点名:property
子节点值:
子节点名:property
子节点值:
开始遍历:bean
节点名:id
节点值:sessionFactory
节点名:class
节点值:org.springframework.orm.hibernate4.LocalSessionFactoryBean
子节点名:property
子节点值:
子节点名:property
子节点值:
org.hibernate.dialect.MySQLDialect true true update
子节点名:property
子节点值:
entity/Employee.hbm.xml entity/Department.hbm.xml
开始遍历:bean
节点名:id
节点值:employeeAction
节点名:class
节点值:action.EmployeeAciton
节点名:scope
节点值:prototype
子节点名:property
子节点值:
子节点名:property
子节点值:
开始遍历:bean
节点名:id
节点值:departmentAction
节点名:class
节点值:action.DepartmentAction
节点名:scope
节点值:prototype
子节点名:property
子节点值:
开始遍历:bean
节点名:id
节点值:employeeService
节点名:class
节点值:service.EmployeeServiceImpl
子节点名:property
子节点值:
开始遍历:bean
节点名:id
节点值:departmentService
节点名:class
节点值:service.DepartmentServiceImpl
子节点名:property
子节点值:
开始遍历:bean
节点名:id
节点值:employeeDAO
节点名:class
节点值:dao.EmployeeDAOImpl
子节点名:property
子节点值:
开始遍历:bean
节点名:id
节点值:departmentDAO
节点名:class
节点值:dao.DepartmentDAOImpl
子节点名:property
子节点值:
开始遍历:bean
节点名:id
节点值:transactionManager
节点名:class
节点值:org.springframework.orm.hibernate4.HibernateTransactionManager
子节点名:property
子节点值:
开始遍历:annotation-driven
节点名:transaction-manager
节点值:transactionManager
四种解析方式进行对比
基础方法:DOM/SAX
-Java自带方法,具有平台无关性-基于事件驱动
DOM解析过程
-将xml文件一次性加载入内存中,并形成DOM树优点
-形成了树结构,直观并且易于理解,代码容易编写-解析过程保留在内存中,方便修改
缺点
-当xml文件较大时,对内存耗费比较大,容易影响解析性能并造成内存溢出SAX解析过程
-基于事件,一步一步解析-每遇到一个标签则进行判断,采用handler中哪种方式进行处理
优点
-采用事件驱动模式,对内存耗费小-适用于只需要处理xml中的数据时
缺点
-不易编码-很难同时访问一个xml中的多处数据
JDOM与DOM/DOM4J
JDOM
-仅使用具体类而不使用接口-API大量使用Collections类
DOM4J
-JDOM的智能分支,合并了许多超出基本xml文档表示的功能-使用接口和抽象基本类的方法,是一个优秀的api
-性能优异,灵活性好,功能强大,易用
-源码开放
-建议使用
性能对比(速度由块到慢)
文件较小时
SAX>DOM>DOM4J>JDOM相关文章推荐
- [Source Code]JAVA I/O --- --- 读取.zip文件,以及zip中的.xml文件
- 项目开发中经常要用到的知识----Java读取.Properties,.Xml,.Ini文件(一)
- java读取数据库字段和值,输出到regedit,xml,text,excel,pdf的程序
- java读取XML
- [转载]JAVA高手解析XML配置文件的读取操作
- [JAVA]XML读取
- JAVA操作XML一(读取):使用DOM读取XML数据的两种具体实现
- java读取xml配置文件(sax)
- java读取XML
- FLASH读取JAVA生成的XML文件,不同平台乱码
- 项目开发中经常要用到的知识----Java读取.Properties,.Xml,.Ini文件(二)
- JAVA技术:XML配置文件的读取处理
- Java读取XML文件之SAX篇
- Java 如何读取sqlserver生成的xml
- 一个java读取word文档并将其写入xml文档的例子
- java读取xml
- JAVA高手解析XML配置文件的读取操作
- Java读取XML文件之SAX篇 (转载)
- JAVA读取xml
- 读取XML文件里其中一个结点的值(Java)