Java讀寫XML

來源:互聯網
上載者:User

匯入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)可得到節點的屬性值

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.