Java读取xml

首先将xml的格式展示出来,如下

<?xml version="1.0"?>
<configuration>
  <connectionStrings name="zhangsan">
    <add name="dbSqlServer" connectionString="Data Source=.;Initial Catalog=Life;User ID=sa;pwd=hzsoft"/>
    <add name="dbAccess" connectionString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|\Life.mdb;"/>
    <add name="dbSqlite" connectionString="Data Source=|DataDirectory|\Life.db3;Pooling=true;FailIfMissing=false" providerName="System.Data.SQLite"/>
  </connectionStrings>  
</configuration>

此处采用的读取方式是DOM4J,需要先下载对应的jar包,具体下载地址如下:http://nchc.dl.sourceforge.net/sourceforge/dom4j/dom4j-1.6.1.zip

java的具体代码如下:

import java.io.File;
import java.util.List;

import org.dom4j.*;
import org.dom4j.io.SAXReader;

public class Hello {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SAXReader reader = new SAXReader();
        File f = new File("D:\\Web.xml");

        try {
            Document document = reader.read(f);
            Element root = document.getRootElement();

            Element conn = root.element("connectionStrings");

            String val = conn.attribute("name").getValue();
            System.out.println(val);

            List list = conn.elements("add");

            for (int i = 0; i < list.size(); i++) {
                Element ele = (Element) list.get(i);
                System.out.println(ele.attribute("connectionString").getValue());
            }

            ///////// foreach实现
            for (Object obj : list) {
                Element ele = (Element) obj;
                System.out.println(ele.attribute("connectionString").getValue());
            }

        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

上面是读取xml文件,写入xml文件的代码如下:

import java.io.*;

import org.dom4j.*;
import org.dom4j.io.*;

public class App {
    public static void main(String[] args) throws IOException {
        Document document = DocumentHelper.createDocument();
        Element root = DocumentHelper.createElement("configuration");
        document.setRootElement(root);

        Element eleConnectionStrings = root.addElement("connectionStrings");
        eleConnectionStrings.addAttribute("name", "zhangsan");

        Element eleAdd = eleConnectionStrings.addElement("add");
        eleAdd.addAttribute("name", "dbSqlServer");

        // 格式化,避免写入文件是一行数据
        OutputFormat opf = new OutputFormat();
        opf.setNewlines(true);
        opf.setIndent(true);
        opf.setEncoding("utf-8");//编码格式
        opf.setIndent("    ");// 使用4个空格进行缩进, 可以兼容文本编辑器

        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("config.xml"), opf);
        xmlWriter.write(document);
        // xmlWriter.flush();
        xmlWriter.close(); //上面的方法无法完全释放资源

    }
}

 

很久没有接触Java了,最近经理说我们公司将技术转型,由以前的C#转Java,因此回顾一下,特此记录

 

posted @ 2017-05-10 21:51  段江涛IT  阅读(370)  评论(0编辑  收藏  举报
页脚HTML代码