zoukankan      html  css  js  c++  java
  • 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);
        }
  • 相关阅读:
    【webpack 系列】进阶篇
    【webpack 系列】基础篇
    手写 Promise 符合 Promises/A+规范
    React-redux: React.js 和 Redux 架构的结合
    Redux 架构理解
    javascript 中的 this 判定
    编译原理
    vue 响应式原理
    强大的版本管理工具 Git
    js实现跨域(jsonp, iframe+window.name, iframe+window.domain, iframe+window.postMessage)
  • 原文地址:https://www.cnblogs.com/gugia/p/5044483.html
Copyright © 2011-2022 走看看