Chinaunix首页 | 论坛 | 博客
  • 博客访问: 488438
  • 博文数量: 111
  • 博客积分: 3146
  • 博客等级: 中校
  • 技术积分: 939
  • 用 户 组: 普通用户
  • 注册时间: 2009-07-07 11:23
个人简介

Nathing

文章分类

全部博文(111)

文章存档

2016年(2)

2015年(1)

2014年(31)

2012年(2)

2011年(9)

2010年(36)

2009年(30)

我的朋友

分类: Java

2010-11-02 16:45:25

1.JDK1.6
2.code

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class Dom
{

    private Element e;

    private Dom(Element element)
    {
        this.e = element;
    }

    public void print()
    {
        NodeList nodeList = e.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++)
        {
            Node node = nodeList.item(i);
            System.out.println("节点名: " + node.getNodeName() + ", 节点值: "
                    + node.getNodeValue() + ", 节点类型: " + node.getNodeType());
        }
    }

    public Element getDomElement()
    {
        return e;
    }

    public static Dom newDom(String rootName) throws XmlException
    {
        Document doc = null;
        try
        {
            DocumentBuilder dombuilder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            doc = dombuilder.newDocument();
            doc.setXmlStandalone(true);
        }
        catch (Exception e)
        {
            throw new XmlException(e.getMessage(), e);
        }
        Element root = doc.createElement(rootName);
        doc.appendChild(root);
        return new Dom(root);
    }

    public static Dom getRoot(InputStream is) throws XmlException
    {
        Document doc = null;
        try
        {
            DocumentBuilder dombuilder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            doc = dombuilder.parse(is);
        }
        catch (Exception e)
        {
            throw new XmlException(e.getMessage(), e);
        }
        Element root = doc.getDocumentElement();
        return new Dom(root);
    }

    public static Dom getRoot(String xmlFile) throws XmlException
    {
        try
        {
            InputStream is = new FileInputStream(xmlFile);
            Dom root = getRoot(is);
            is.close();
            return root;
        }
        catch (Exception e)
        {
            throw new XmlException(e.getMessage(), e);
        }
    }

    public String getAttributeValue(String attributeName)
    {
        return e.getAttribute(attributeName);
    }

    public boolean existElement(String elementName)
    {
        NodeList nodeList = e.getElementsByTagName(elementName);
        if ((nodeList == null) || (nodeList.getLength() < 1))
        {
            return false;
        }
        return true;
    }

    public String elementText(String elementName)
    {
        Element element = (Element) e.getElementsByTagName(elementName).item(0);
        Node textNode = element.getFirstChild();
        if (textNode == null)
        {
            return "";
        }
        return textNode.getNodeValue();
    }

    public Dom element(String elementName)
    {
        NodeList nodeList = e.getElementsByTagName(elementName);
        if ((nodeList == null) || (nodeList.getLength() < 1))
        {
            return null;
        }
        Element element = (Element) nodeList.item(0);
        return new Dom(element);
    }

    public List<Dom> elements(String elementName)
    {
        List<Dom> eList = new ArrayList<Dom>();
        NodeList nodeList = e.getElementsByTagName(elementName);
        if (nodeList == null)
        {
            return eList;
        }
        for (int i = 0; i < nodeList.getLength(); i++)
        {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE)
            {
                Element element = (Element) node;
                eList.add(new Dom(element));
            }
        }
        return eList;
    }

    public Dom addElement(String name)
    {
        Document document = e.getOwnerDocument();
        Element element = document.createElement(name);
        e.appendChild(element);
        return new Dom(element);
    }

    public Dom addElement(String name, String value)
    {
        Document document = e.getOwnerDocument();
        Element element = document.createElement(name);
        e.appendChild(element);
        Text text = document.createTextNode(value);
        element.appendChild(text);
        return new Dom(element);
    }

    // 添加或修改属性

    public Dom setAttribute(String name, String value)
    {
        e.setAttribute(name, value);
        return this;
    }

    public void remove(Dom subDom)
    {
        e.removeChild(subDom.getDomElement());
    }

    public void removeElement(String name)
    {
        NodeList nodeList = e.getElementsByTagName(name);
        if (nodeList == null)
        {
            return;
        }
        for (int i = 0; i < nodeList.getLength(); i++)
        {
            e.removeChild(nodeList.item(i));
        }
    }

    public void removeAttribute(String name)
    {
        e.removeAttribute(name);
    }

    public Dom updateElementText(String name, String value)
    {
        Element element = (Element) e.getElementsByTagName(name).item(0);
        Node textNode = element.getFirstChild();
        textNode.setNodeValue(value);
        return new Dom(element);
    }

    public Dom updateElementText(String value)
    {
        Node textNode = e.getFirstChild();
        textNode.setNodeValue(value);
        return this;
    }

    public String getElementText()
    {
        Node textNode = e.getFirstChild();
        return textNode.getNodeValue();
    }

    public void write(OutputStream os)
    {
        write(os, "UTF-8");
    }

    public void write(OutputStream os, String encoding)
    {
        try
        {
            TransformerFactory tFactory = TransformerFactory.newInstance();
            tFactory.setAttribute("indent-number", 2);
            Transformer transformer = tFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
            transformer.transform(new DOMSource(e.getOwnerDocument()),
                    new StreamResult(new OutputStreamWriter(os)));
        }
        catch (TransformerConfigurationException e)
        {
            e.printStackTrace();
        }
        catch (TransformerFactoryConfigurationError e)
        {
            e.printStackTrace();
        }
        catch (TransformerException e)
        {
            e.printStackTrace();
        }
    }

    public void write(String xmlFile) throws XmlException
    {
        write(xmlFile, "UTF-8");
    }

    public void write(String xmlFile, String encoding) throws XmlException
    {
        try
        {
            OutputStream os = new FileOutputStream(xmlFile);
            write(os, encoding);
            os.close();
        }
        catch (Exception e)
        {
            throw new XmlException(e.getMessage(), e);
        }
    }

}

class XmlException extends RuntimeException
{

    private static final long serialVersionUID = 1L;

    public XmlException(String message)
    {
        super(message);
    }

    public XmlException(String message, Throwable cause)
    {
        super(message, cause);
    }
}


3.用法:

//1>解析xml
    public void testGetElements()
    {
        Dom root = Dom.getRoot("d:/test.xml");

        List<Dom> pList = root.elements("property");

        for (Dom d : pList)
        {
            System.out.println(d.elementText("name") + ", "+ d.elementText("value") + ", "
                    + d.elementText("description"));
        }
    }
    
    //2>修改xml
    public void testUpdateElementText()
    {
        Dom root = Dom.getRoot("d:/test.xml");
        List<Dom> pList = root.elements("property");
        
        Dom d = pList.get(0);
        Dom nameDom = d.element("name");
        nameDom.setAttribute("a", "2");
        nameDom.setAttribute("b", "3");
        nameDom.updateElementText("测试呵呵");
        d.updateElementText("description", "按当地");

        root.write("d:/test.xml");
    }
    
    //3>新建xml
    public void testNewDom()
    {
        Dom root = Dom.newDom("configuration");
        Dom propertyDom = root.addElement("property");
        propertyDom.addElement("name", "名称");
        propertyDom.addElement("value", "值");
        Dom dDom = propertyDom.addElement("description", "描述");
        dDom.setAttribute("a", "2");
        root.write("d:/test.xml");
    }


附件:1-->test.xml

<?xml version="1.0" encoding="UTF-8"?>

<configuration>

<property>
  <name a="1">host</name>
  <value>http://192.168.3.249</value>
  <description>系统主机地址</description>
</property>

<property>
  <name>login</name>
  <value>/page/Default.aspx</value>
  <description>登陆页面</description>
</property>

</configuration>


2-->修改后的xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<configuration>

<property>
  <name a="2" b="3">测试呵呵</name>
  <value>http://192.168.3.249</value>
  <description>按当地</description>
</property>

<property>
  <name>login</name>
  <value>/page/Default.aspx</value>
  <description>登陆页面</description>
</property>

</configuration>


3-->新建的xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration>
  <property>
    <name>名称</name>
    <value></value>
    <description a="2">描述</description>
  </property>
</configuration>


阅读(1612) | 评论(1) | 转发(0) |
0

上一篇:Ibtis

下一篇:Strategy策略模式

给主人留下些什么吧!~~

chinaunix网友2010-11-05 08:41:21

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com