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

时间:2020-12-24 08:26:04

首先,贴上自己的实例:

XML文件:NewFile.xml(该文件与src目录同级)

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property>
<name>s3Bucket</name>
<value></value>
<description>get s3Bucket to get data</description>
</property>
<property>
<name>s3key</name>
<value>2016-12-19/12:26:36</value>
<description></description>
</property>
<property>
<name>DynamoDBTable</name>
<value>longyauntest</value>
<description></description>
</property>
<property>
<name>KINESIS_STREAM_NAME</name>
<value></value>
<description></description>
</property>
<property>
<name>Region</name>
<value>cn-north-1</value>
<description></description>
</property>
<property>
<name>LogFilePath</name>
<value></value>
<description>save logfile to somewhere in s3
eg:s3bucket://prefix key.</description>
</property>
</configuration>

读取类:

String CONFIGXML_FILEPATH="NewFile.xml";
Map<String, String> propertyMap = new HashMap<String, String>();
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(CONFIGXML_FILEPATH);
// 获取根元素
Element configuration = doc.getDocumentElement(); // System.out.println(rootElement); // 获取根元素下面的子节点列表
NodeList propertyList = configuration.getChildNodes(); for (int i = 0; i < propertyList.getLength(); i++) {
// 获取每个子节点
Node property = propertyList.item(i); String propertyName = null;
String propertyValue = null; //该list包括单个property中的各个子节点,包括name、value、description
NodeList nodeList = property.getChildNodes();
// 遍历该节点的详细信息
for (int j = 0; j < nodeList.getLength(); j++) {
Node propertyDetail = nodeList.item(j); if (!propertyDetail.getNodeName().equals("#text")) {
// 获取属性名
if (propertyDetail.getNodeName().equals("name")) {
propertyName = propertyDetail.getTextContent();
}
// 获取属性值
if (propertyDetail.getNodeName().equals("value")) {
propertyValue = propertyDetail.getTextContent();
}
}
}
// 如果属性值不为null,则将属性放入map中
if (propertyValue != null) {
PropertyMap.put(propertyName, propertyValue);
System.out.println(propertyName + ":" + propertyValue);
}
}

         //打印
// for(String key:property.keySet())
// {
// System.out.println(key+":"+property.get(key));
// } } catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

ok,以下是别人的:

1.java读取xml文件的四种方法

2.四种生成和解析XML文档的方法详解(介绍+优缺点比较+示例)(这个妹纸比较6)

3.java解析xml文件(三种方式-(dom ,jdom ,dom4j)