返回顶部

收藏

JDOM 实现的 XMLProperties 类

更多
package javaxml3;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class XMLProperties extends Properties {

    public void load(Reader reader) 
    throws IOException {

    try { 
        // Load XML into JDOM Document
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(reader);

        // Turn into properties objects
        loadFromElements(doc.getRootElement().getChildren(), 
            new StringBuffer(""));

    } catch (JDOMException e) {
        throw new IOException(e.getMessage());
    }        
}

private void loadFromElements(List elements, StringBuffer baseName) {
    // Iterate through each element
    for (Iterator i = elements.iterator(); i.hasNext(); ) {
        Element current = (Element)i.next();
        String name = current.getName();
        String text = current.getTextNormalize();

        // Don't add "." if no baseName
        if (baseName.length() > 0) {
            baseName.append(".");
        }            
        baseName.append(name);

        // See if we have an element value
        if ((text == null) || (text.equals(""))) {
            // If no text, recurse on children
            loadFromElements(current.getChildren(),
                             baseName);
        } else {                
            // If text, this is a property
            setProperty(baseName.toString(), 
                        text);
        }            

        // On unwind from recursion, remove last name
        if (baseName.length() == name.length()) {
            baseName.setLength(0);
        } else {                
            baseName.setLength(baseName.length() - 
                (name.length() + 1));
        }            
    }        
}

    public void load(InputStream inputStream) throws IOException {

        load(new InputStreamReader(inputStream));
    }

    public void load(File xmlDocument) throws IOException {

        load(new FileReader(xmlDocument));
    }

    public void save(OutputStream out, String header) {
        try {
            store(out, header);
        } catch (IOException ignored) {
            // Deprecated version doesn't pass errors
        }
    }

    public void store(Writer writer, String header) throws IOException {

        // Create a new JDOM Document with a root element "properties"
        Document doc = new Document();
        Element root = new Element("properties");
        doc.setRootElement(root);

        // Add in header information
        Comment comment = new Comment(header);
        doc.getContent().add(0, comment);

        // Get the property names
        Enumeration propertyNames = propertyNames();
        while (propertyNames.hasMoreElements()) {
            String propertyName = (String) propertyNames.nextElement();
            String propertyValue = getProperty(propertyName);
            createXMLRepresentation(root, propertyName, propertyValue);
        }

        // Output document to supplied filename
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        outputter.output(doc, writer);
    }

    private void createXMLRepresentation(Element root, String propertyName,
            String propertyValue) {

        int split;
        String name = propertyName;
        Element current = root;
        Element test = null;

        while ((split = name.indexOf(".")) != -1) {
            String subName = name.substring(0, split);
            name = name.substring(split + 1);

            // Check for existing element
            if ((test = current.getChild(subName)) == null) {
                Element subElement = new Element(subName);
                current.addContent(subElement);
                current = subElement;
            } else {
                current = test;
            }
        }

        // When out of loop, what's left is the final element's name
        Element last = new Element(name);
        last.setText(propertyValue);
        /** Uncomment this for Attribute usage */
        /*
         * last.setAttribute("value", propertyValue);
         */
        current.addContent(last);
    }

    public void store(OutputStream out, String header) throws IOException {

        store(new OutputStreamWriter(out), header);
    }

    public void store(File xmlDocument, String header) throws IOException {

        store(new FileWriter(xmlDocument), header);
    }
}

//该片段来自于http://outofmemory.cn

标签:java,基础

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. 逍遥冲 发表 2013-11-17 14:31:47 Google Guava EventBus实例与分析
  2. 博主 发表 2015-04-10 02:35:00 titanium module java基础: 记得使用annotation
  3. 博主 发表 2015-12-29 07:29:15 java 基础
  4. 博主 发表 2013-08-26 02:35:24 JAVA操作Hbase基础例子
  5. Terry Zhang 发表 2014-04-27 08:18:40 [集合框架] Java 集合框架简介
  6. Terry Zhang 发表 2014-05-02 08:58:00 [集合框架] Set 接口
  7. 博主 发表 2015-04-11 02:32:00 titanium module java基础: 从js到java的类型转换。
  8. 郑 旭东 发表 2014-01-16 16:46:51 JAVA多线程和并发基础面试问答
  9. Terry Zhang 发表 2014-04-17 15:27:06 [正则] 字符类型
  10. Terry Zhang 发表 2014-04-27 10:43:29 [集合框架] 接口
  11. 逍遥冲 发表 2013-12-05 05:53:28 [引]Java NIO —- IO复用
  12. root 发表 2015-04-21 04:58:01 Java 7之基础 – 强引用、弱引用、软引用、虚引用

发表评论