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);
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM