Java读写XML

导入jdom.jar,jdom提供了比较简单易用的读写xml文件的方法

一、写XML

示例:

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

public class XmlWriter {

        private Element wRoot = null;

        private Document wDoc = null;

        public void initwRoot() {

        try {

             wRoot = new Element("database");

             wDoc = new Document(wRoot);

        }

        catch (Exception e) {

             e.printStackTrace();

        }

       }

      public void writeXml(String strFileName) {

      try {

           File f = new File(strFileName);

           if(f.exists()){

                  f.delete();

           }

          f.createNewFile();

         XMLOutputter XMLOut = new XMLOutputter();

         XMLOut.output(wDoc, new FileOutputStream(strFileName));

       }

      catch (Exception e) {

          e.printStackTrace();

      }

      }

}

在XML中添加节点:

public Element addNode(Element eCur, String nodename){

          Element eChild = null;

         try{

             eChild = new Element(nodename);

            eCur.addContent(eChild);

         }

         catch(Exception e){

            e.printStackTrace();

         }

          return eChild;

}

通过上述方法得到文档对象wDoc,以及其根节点wRoot, 调用方法addNode()可以往根节点中插入子节点,返回的子节点对象eChild,同理,可以往子节点eChild中插入下一级的子节点。最后调用writeXml()方法保存为xml文件

 

二、读XML

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class XmlReader {

  private Element rRoot = null;

 

  public void initrRoot(String strXMLPathFile) throws IOException, JDOMException {

            SAXBuilder builder = new SAXBuilder();

            Document read_doc = builder.build(strXMLPathFile);

            rRoot = read_doc.getRootElement();

  }

}

通过上述代码得到xml文件的根节点rRoot,接下来可以调用rRoot的List<Element> getChildren(String nodeName) 方法得到其子节点,同理,可以依次遍历各个子节点的getChilren()方法;通过Element的String getAttributeValue(String attrName)可得到节点的属性值

 

 

posted @ 2013-01-04 13:19  闲时乱翻书  阅读(256)  评论(0)    收藏  举报