撑持链式方法生成/解析XML的Java类库 (依靠dom4j) - 代码共享

[代码] [Java]代码 import java.io.*;
import java.util.List;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.collections.Transformer;
import org.dom4j.*;
import org.dom4j.io. http://www.1111kp.info/linked/20130325.do *;

public class XmlNode {

    private static final Transformer transformer = new Transformer() {
        @Override
        public Object transform(Object node) {
            return wrap((Element) node);
        }
    };

    private final Element node;

    /**
     * Read a xml document and get root element.
     * 
     * @param file
     */
    public static XmlNode create(File file) {
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(file);
            return wrap(doc.getRootElement());
        } catch (DocumentException e) {
            throw uncheckThrowable(e);
        }
    }

    /**
     * Read a xml document and get root element.
     */
    public static XmlNode create(InputStream is) {
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(is);
            return wrap(doc.getRootElement());
        } catch (DocumentException e) {
            throw uncheckThrowable(e);
        }
    }

    /**
     * Create a xml node with name.
     */
    public static XmlNode create(String tagName) {
        return wrap(DocumentHelper.createElement(tagName));
    }

    /**
     * Parses the given text as an XML document and returns the newly created
     * root node.
     */
    public static XmlNode parseXml(String xml) {
        try {
            Document document = DocumentHelper.parseText(xml);
            return wrap(document.getRootElement());
        } catch (DocumentException e) {
            throw uncheckThrowable(e);
        }
    }

    private static XmlNode wrap(Element node) {
        if (node == null) {
            return null;
        }
        return new XmlNode(node);
    }

    private XmlNode(Element node) {
        this.node = node;
    }

    public String getName() {
        return node.getName();
    }

    public void setName(String value) {
        node.setName(value);
    }

    public String getText() {
        return node.getTextTrim();
    }

    public void setText(String value) {
        node.setText(value);
    }

    /**
     * Get a unique xpath expression.
     * 
     * @return
     */
    public String getPath() {
        return node.getUniquePath();
    }

    public XmlNode getParent() {
        return wrap(node.getParent());
    }

    public boolean isRoot() {
        return node.isRootElement();
    }

    /**
     * Return the new added node.
     * 
     * @param tagName
     * @return
     */
    public XmlNode addNode(String tagName) {
        return wrap(node.addElement(tagName));
    }

    /**
     * Remove node from parent
     */
    public void remove() {
        if (node.getParent() != null) {
            node.getParent().remove(node);
        }
    }

    public XmlNode element(String tagName) {
        return wrap(node.element(tagName));
    }

    /**
     * Equals element(tagName).getText().
     */
    public String elementText(String tagName) {
        return node.elementTextTrim(tagName);
    }

    public List elements() {
        return ListUtils.transformedList(node.elements(), transformer);
    }

    public List elements(String tagName) {
        return ListUtils.transformedList(node.elements(tagName), transformer);
    }

    public XmlNode selectSingleNode(String xpath) {
        return wrap((Element) node.selectSingleNode(xpath));
    }

    public List selectNodes(String xpath) {
        return ListUtils.transformedList(node.selectNodes(xpath), transformer);
    }

    public List attributes() {
        return ListUtils.transformedList(node.attributes(), XmlAttribute.transformer);
    }

    public XmlAttribute attribute(String name) {
        return new XmlAttribute(node.attribute(name));
    }

    /**
     * Set the attribute value of the given name.
* If value is null, the attribute will be removed. * * @param name * @param value */ public XmlNode attribute(String name, Object value) { if (value == null) { node.addAttribute(name, null); } else { node.addAttribute(name, value.toString()); } return this; } public String asXml() { return node.asXML(); } public String asFormatedXml() { try { OutputFormat format = OutputFormat.createPrettyPrint(); Writer out = new StringWriter(); XMLWriter writer = new XMLWriter(out, format); writer.write(node); writer.close(); return out.toString(); } catch (IOException e) { throw uncheckThrowable(e); } } public void write(OutputStream out, String encoding) { try { Document document = DocumentHelper.createDocument(node); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(encoding); XMLWriter writer = new XMLWriter(out, format); writer.write(document); } catch (IOException e) { throw uncheckThrowable(e); } } private RuntimeException uncheckThrowable(Throwable e) { return e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e); } public static class XmlAttribute { private static final Transformer transformer = new Transformer() { @Override public Object transform(Object node) { return new XmlAttribute((Attribute) node); } }; private final Attribute attr; public XmlAttribute(Attribute attr) { this.attr = attr; } public boolean exist() { return attr != null; } public String name() { return exist() ? attr.getName() : null; } public String value() { return exist() ? attr.getValue() : null; } public String asString() { return value(); } public String asString(String defaultValue) { return exist() ? attr.getValue() : defaultValue; } public Integer asInt() { return exist() ? Integer.valueOf(attr.getValue()) : null; } public Integer asInt(int defaultValue) { return exist() ? Integer.valueOf(attr.getValue()) : defaultValue; } public Double asDouble() { return exist() ? Double.valueOf(attr.getValue()) : null; } public Double asDouble(double defaultValue) { return exist() ? Double.valueOf(attr.getValue()) : defaultValue; } public Boolean asBoolean() { return exist() ? Boolean.valueOf(attr.getValue()) : null; } public Boolean asBoolean(boolean defaultValue) { return exist() ? Boolean.valueOf(attr.getValue()) : defaultValue; } } } http://www.aaafaipiao.com/linked/20130325.do
posted @ 2013-03-26 05:36  chinadiy197601  阅读(312)  评论(0编辑  收藏  举报