XML读取 java

背景

感觉忙了好几天,但是回头看看却什么也没有忙

唯有写博客才觉得充实

之前看一个框架很有意思,将很多配置文件都写到xml文件中,如果系统中使用到读取xml中的配置文件

为什么不用properties这样的配置文件,我感觉是中文的问题

所以我把自己项目的config.properties也转换为config.xml这样的配置文件,这样增加备注也中文也方便查看

配置文件在classpath路径下:

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

	<!-- 日志发送地址 -->

	<prop name="SPBMJCBZ">1</prop>

	<!--本地生成pdf下载地址 -->
	<prop name="downloadpath">http://localhost:8010/system2/</prop>
	
	<!-- linux系统当前保存路径 -->
	<prop name="linux_path">/home/webapps/</prop>
	
	<!-- 日志存储路径-->
	
	<prop name="commonslog">/home/tmp/</prop>
	<prop name="catalinalog">OFD</prop>
    <prop name="localhostlog">OFD</prop>

</root>

读取

package com.hangxin.basic.util;

import java.io.IOException;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class XMLUtils {
	/**
	 * 
	 * @param attr 对应的name属性
	 * @return
	 */

	public static String getValueByName(String attr) {

		try {

			String text = null;
			Resource cr = new ClassPathResource("config.xml");
			SAXReader saxReader = new SAXReader();
			// 读取文件
			Document read;
			read = saxReader.read(cr.getInputStream());
			// 获取根节点
			Element rootElement = read.getRootElement();
			Iterator<Element> itertor = rootElement.elementIterator();
			while (itertor.hasNext()) {
				Element element = itertor.next();
				if (attr.equals(element.attribute("name").getValue())) {
					text = element.getText();
					break;
				}
			}
			return text;

		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		System.out.println(getValueByName("softname"));
	}
}

上面便是对xml的读取

希望对你有所帮助!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值