Spring读写xml文件

一、如果只是读取

新建一个 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);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值