一、如果只是读取
新建一个 xml 文件,需要满足Spring格式:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
"> <bean class="com.example.Config">
<property name="Address">
<value>中国四川省绵阳市</value>
</property>
</bean>
</beans>
创建一个类,类的路径与上面xml文件中的class一致:
package com.example public class Config { public static String address;
public void setAddress(String addr) {
address = addr;
}
}
然后将 config.xml 引入到Spring主配置文件中:
<import resource="config.xml"/>
测试:
System.out.println(Config.address);
看看输出结果是不是“中国四川省绵阳市”。
二、读写
以config.xml为例:
<config>
<Address>中国四川省绵阳市</Address>
</config>
这时需要用到 jdom,代码如下:
/* 引入项
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.springframework.core.io.ClassPathResource;
*/
private String readServerConfig(String configFileName) throws Exception {
ClassPathResource resource = new ClassPathResource(configFileName);
Document doc = new SAXBuilder().build(resource.getFile());
Element root = doc.getRootElement();
Element element = root.getChild("Address");
return element.getText();
} private void writeServerConfig(String configFileName) throws Exception {
ClassPathResource resource = new ClassPathResource(configFileName);
Document doc = new SAXBuilder().build(resource.getFile());
Element root = doc.getRootElement();
Element element = root.getChild("Address");
element.setText("中国四川省成都市");
root.setContent(element);
}