【XML配置文件读取】使用jdom读取XML配置文件信息
配置文件信息

<?xml version="1.0" encoding="UTF-8"?>
<config>
<base-config>
<stringValue>Hello world</stringValue>
<integerValue>8</integerValue>
<longValue>32768</longValue>
</base-config>
<books>
<book id="111">
<name>Java 编程</name>
<price>33</price>
</book>
<book id="222">
<name>Spring学习指南</name>
<price>55</price>
</book>
</books>
<computers>
<computer type="dell" size="14寸" />
<computer type="thinkpad" size="16寸" />
<computer type="apple" size="22寸" />
</computers>
</config>
需要的Jar包(MAVEN给出)


完整的POM文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ll</groupId>
<artifactId>myThreadStudy</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>myThreadStudy</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junitVersion>3.8.1</junitVersion>
<commons-io-Version>2.4</commons-io-Version>
<jaxenVersion>1.1.1</jaxenVersion>
<jdomVersion>1.1</jdomVersion>
<log4jVersion>1.2.17</log4jVersion>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junitVersion}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io-Version}</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>${jdomVersion}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4jVersion}</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>${jaxenVersion}</version>
</dependency>
</dependencies>
<build>
<defaultGoal>install</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding> <!-- “编码 GBK 的不可映射字符”问题的解决 -->
</configuration>
</plugin>
</plugins>
</build>
</project>
通用的XML操作类(XMLOperatorUtils.java)
package com.ll.myThreadStudy.MyThread;
import java.util.List;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;
public class XMLOperatorUtils {
public static String getElementAttributeStringValue(Element element,
String AttributeName) {
try {
return element.getAttributeValue(AttributeName);
} catch (Exception e) {
return null;
}
}
public static Integer getElementAttributeIntegerValue(Element element,
String AttributeName) {
try {
return Integer.parseInt(getElementAttributeStringValue(element,
AttributeName));
} catch (Exception e) {
return -1;
}
}
public static Long getElementAttributeLongValue(Element element,
String AttributeName) {
try {
return Long.parseLong(getElementAttributeStringValue(element,
AttributeName));
} catch (Exception e) {
return -1l;
}
}
public static Boolean getElementAttributeBooleanValue(Element element,
String AttributeName) {
try {
return Boolean.parseBoolean(getElementAttributeStringValue(element,
AttributeName));
} catch (Exception e) {
return false;
}
}
public static String getElementTextStringValueFromRoot(Element rootEle,
String path) {
try {
return ((Element) getSingleNode(rootEle, path)).getTextTrim();
} catch (Exception e) {
return null;
}
}
public static Integer getElementTextIntegerValueFromRoot(Element rootEle,
String path) {
try {
return Integer.parseInt(getElementTextStringValueFromRoot(rootEle,
path));
} catch (Exception e) {
return -1;
}
}
public static Long getElementTextLongValueFromRoot(Element rootEle,
String path) {
try {
return Long.parseLong(getElementTextStringValueFromRoot(rootEle,
path));
} catch (Exception e) {
return -1l;
}
}
public static Boolean getElementTextBooleanValueFromRoot(Element rootEle,
String path) {
try {
return Boolean.parseBoolean(getElementTextStringValueFromRoot(
rootEle, path));
} catch (Exception e) {
return false;
}
}
public static String getElementTextStringValueByElement(Element element,
String childName) {
try {
return element.getChildText(childName);
} catch (Exception e) {
return null;
}
}
protected static Integer getElementTextIntegerValueByElement(
Element element, String childName) {
try {
return Integer.parseInt(getElementTextStringValueByElement(element,
childName));
} catch (Exception e) {
return -1;
}
}
protected static Long getElementTextLongValueByElement(Element element,
String childName) {
try {
return Long.parseLong(getElementTextStringValueByElement(element,
childName));
} catch (Exception e) {
return -1l;
}
}
protected static Boolean getElementTextBooleanValueByElement(
Element element, String childName) {
try {
return Boolean.parseBoolean(getElementTextStringValueByElement(
element, childName));
} catch (Exception e) {
return false;
}
}
protected static Object getSingleNode(Element rootEle, String path)
throws JDOMException {
return XPath.selectSingleNode(rootEle, path);
}
@SuppressWarnings("rawtypes")
protected static List getNodes(Element rootEle, String path)
throws JDOMException {
return XPath.selectNodes(rootEle, path);
}
}
读取配置文件到Java POJO
package com.ll.myThreadStudy.MyThread;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
public class XmlToConfigVO {
private static Logger logger = Logger.getLogger(XmlToConfigVO.class);
public static MyConfigVo getLogSystemConfigVO(String fileName) {
try {
Element rootEle = new SAXBuilder().build(new File(fileName))
.getRootElement();
MyConfigVo myConfigVo = new MyConfigVo();
//获取单个节点值的内容
myConfigVo.setStringValue(XMLOperatorUtils
.getElementTextStringValueFromRoot(rootEle,
"/config/base-config/stringValue"));
myConfigVo.setIntegerValue(XMLOperatorUtils
.getElementTextIntegerValueFromRoot(rootEle,
"/config/base-config/integerValue"));
myConfigVo.setLongValue(XMLOperatorUtils
.getElementTextLongValueFromRoot(rootEle,
"/config/base-config/longValue"));
//获取多个节点值
HashMap<Integer, BookVo> booksMap = new HashMap<Integer, BookVo>();
for (Object element : XPath.selectNodes(rootEle,"/config/books/book")) {
BookVo book = new BookVo();
book.setId(XMLOperatorUtils.getElementAttributeIntegerValue((Element) element,"id"));
book.setName(XMLOperatorUtils.getElementTextStringValueByElement((Element) element,"name"));
book.setPrice(XMLOperatorUtils.getElementTextLongValueByElement((Element) element,"price"));
booksMap.put(book.getId(),book);
}
myConfigVo.setBooksMap(booksMap);
List<ComputerVo> computerList= new ArrayList<ComputerVo>();
for (Object element : XPath.selectNodes(rootEle,"/config/computers/computer")) {
ComputerVo computer = new ComputerVo();
computer.setType(XMLOperatorUtils.getElementAttributeStringValue((Element) element, "type"));
computer.setSize(XMLOperatorUtils.getElementAttributeStringValue((Element) element,"size"));
computerList.add(computer);
}
myConfigVo.setComputerList(computerList);
return myConfigVo;
} catch (Exception e) {
logger.error(e);
}
return null;
}
}
完整程序

package com.ll.myThreadStudy.MyThread;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MyConfigVo {
private String stringValue;
private Integer integerValue;
private Long longValue;
private HashMap<Integer, BookVo> booksMap = new HashMap<Integer, BookVo>();
private List<ComputerVo> computerList = new ArrayList<ComputerVo>();
public String getStringValue() {
return stringValue;
}
public void setStringValue(String stringValue) {
this.stringValue = stringValue;
}
public Integer getIntegerValue() {
return integerValue;
}
public void setIntegerValue(Integer integerValue) {
this.integerValue = integerValue;
}
public Long getLongValue() {
return longValue;
}
public void setLongValue(Long longValue) {
this.longValue = longValue;
}
public HashMap<Integer, BookVo> getBooksMap() {
return booksMap;
}
public void setBooksMap(HashMap<Integer, BookVo> booksMap) {
this.booksMap = booksMap;
}
public List<ComputerVo> getComputerList() {
return computerList;
}
public void setComputerList(List<ComputerVo> computerList) {
this.computerList = computerList;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((booksMap == null) ? 0 : booksMap.hashCode());
result = prime * result
+ ((computerList == null) ? 0 : computerList.hashCode());
result = prime * result
+ ((integerValue == null) ? 0 : integerValue.hashCode());
result = prime * result
+ ((longValue == null) ? 0 : longValue.hashCode());
result = prime * result
+ ((stringValue == null) ? 0 : stringValue.hashCode());
return result;
}
@Override
public String toString() {
return "MyConfigVo [stringValue=" + stringValue + ", integerValue="
+ integerValue + ", longValue=" + longValue + ", booksMap="
+ booksMap + ", computerList=" + computerList + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyConfigVo other = (MyConfigVo) obj;
if (booksMap == null) {
if (other.booksMap != null)
return false;
} else if (!booksMap.equals(other.booksMap))
return false;
if (computerList == null) {
if (other.computerList != null)
return false;
} else if (!computerList.equals(other.computerList))
return false;
if (integerValue == null) {
if (other.integerValue != null)
return false;
} else if (!integerValue.equals(other.integerValue))
return false;
if (longValue == null) {
if (other.longValue != null)
return false;
} else if (!longValue.equals(other.longValue))
return false;
if (stringValue == null) {
if (other.stringValue != null)
return false;
} else if (!stringValue.equals(other.stringValue))
return false;
return true;
}
}
package com.ll.myThreadStudy.MyThread;
public class ComputerVo {
private String type;
private String size;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
@Override
public String toString() {
return "ComputerVo [type=" + type + ", size=" + size + "]";
}
}
package com.ll.myThreadStudy.MyThread;
public class BookVo {
private Integer id;
private String name;
private Long price;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getPrice() {
return price;
}
public void setPrice(Long price) {
this.price = price;
}
@Override
public String toString() {
return "BookVo [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
测试文件
package com.ll.myThreadStudy.MyThread;
public class Main {
public static void main(String args[]) {
MyConfigVo myConfigVo = XmlToConfigVO.getLogSystemConfigVO("d:\\myConfig.xml");
System.out.println(myConfigVo);
}
}
测试结果

附件列表
【XML配置文件读取】使用jdom读取XML配置文件信息的更多相关文章
- web.xml中通过contextConfigLocation的读取spring的配置文件
web.xml中通过contextConfigLocation的读取spring的配置文件 博客分类: web.xml contextConfigLocationcontextparamxmlvalu ...
- spring boot 项目从配置文件中读取maven 的pom.xml 文件标签的内容。
需求: 将pom.xml 文件中的版本号读取到配置文件并打印到日志中. 第一步: 在pom.xml 中添加以下标签. 第二步: 将version 标签的值读取到配置文件中 这里使用 @@ 而不是 ...
- 使用JDom解析XML文档模拟Spring的配置文件解析
在J2EE项目中可能会涉及到一些框架的使用,最近接触到了SSH,拿Spring来说配置文件的使用是相当重要的,Spring的配置文件是一个xml文件,Spring是如何读取到配置文件并进行依赖注入的呢 ...
- Jdom读取XML文件
学习Spring时,我们经常看到很多xml配置文件,Spring通过在配置文件中的配置,使用IOC(控制反转),从而实现代码的灵活性,本篇我就为大家介绍一种解析xml方式--Jdom 首先我们到Jdo ...
- 用JDOM读取XML文件
用JDOM读取XML文件需先用org.jdom.input.SAXBuilder对象的build()方法创建Document对象,然后用Document类.Element类等的方法读取所需的内容.IB ...
- JDOM读取xml
[摘 要]JDOM是一个开源项目,它基于树型结构,利用纯JAVA的技术对XML文档实现解析.生成.序列化以及多种操作. 一.JDOM 简介 JDOM是一个开源项目,它基于树型结构,利用纯JAVA的技术 ...
- mybatis源码-解析配置文件(一)之XML的DOM解析方式
目录 简介 Java 中 XML 文件解析 解析方式 DOM 解析 XML 新建 XML 文件 DOM 操作相关类 Java 读取 XML 文件 一起学 mybatis @ 简介 在之前的文章< ...
- 配置文件——App.config文件读取和修改
作为普通的xml文件读取的话,首先就要知道怎么寻找文件的路径.我们知道一般配置文件就在跟可执行exe文件在同一目录下,且仅仅在名称后面添加了一个.config 因此,可以用Application.Ex ...
- Asp.Net Core 3.1学习-读取、监听json配置文件(7)
1.前言 文件配置提供程序默认的给我们提供了ini.json.Xml等.都是读取不同格式的文件.文件配置提供程序支持文件可寻.必选.文件变更的监视. 2.读取配置文件 主要运用的包:需要Ini.xml ...
- Java中XML格式的字符串4读取方式的简单比较
Java中XML格式的字符串4读取方式的简单比较 1.java自带的DOM解析. import java.io.StringReader; import javax.xml.parsers.Docum ...
随机推荐
- c++ 字符窜切割
std::vector<std::string> Tools::SplitStr(const char* baseStr, const char* rule) { log("ba ...
- Mapnik 编译安装过程
首先总结一下,Linux(windows上没有测试过)上Mapnik的编译与测试就是一部心酸血泪史呀,如果您没有做好思想准备,那就出门左转,看点有意思的去吧,编译这个太煎熬了. 安装PostgreSQ ...
- c# 多语言实现 与 InitializeCulture
在实现多语言的时候,我们会使用GetGlobalResourceObject,在服务器控件中显示多语言文本要使用<%$ Resources:Common, Export %>, 但是在设置 ...
- 灰度图像的自动阈值分割(Otsu 法)(转载)
灰度图像的自动阈值分割(Otsu 法) 机器视觉领域许多算法都要求先对图像进行二值化.这种二值化操作阈值的选取非常重要.阈值选取的不合适,可能得到的结果就毫无用处.今天就来讲讲一种自动计算阈值的方法. ...
- Post和get乱码
post 在web.xml中添加 <filter> <filter-name>CharacterEncodingFilter</filter-name> <f ...
- 准备开始自己搞企业管理软件,从openerp入手
公司运行了半年多,人还比较少,只用了一些即时通讯工具,还有svn等基本的工具 记账用的是gnucash 其他的管理急需相应的软件,找了很长时间也没有合适的 想了想,还是从开源的openerp odoo ...
- Codeforces Round #155 (Div. 2)
A. Cards with Numbers 模拟. B. Jury Size 相当于统计单天最大需要人数,会发生变化的点在区间两端,枚举计算即可. C. Anagram 从小到大枚举字母: 若当前字母 ...
- php文件删除
<?php $dirname="shangchuan/uploads"; deldir($dirname); function deldir($dirname){ if(fi ...
- HDU-4777 Rabbit Kingdom(区间更新求和)
题目大意:给一个n个整数的数列,q次询问,每次询问区间[l,r]中与区间中其它数互质的数的个数.. 题目分析:离线处理,这里以询问区间的左端点从小到大的顺序为例.为了叙述方便,用f(l,r)表示区间[ ...
- CentOS搭建LNMP环境
安装开发工具包: yum groupinstall -y "Development Tools*" 50多个,安装了好久…… 下载Nginx: http://nginx.org/e ...