*Java操作XML檔案

來源:互聯網
上載者:User

在java環境下讀取xml檔案的方法主要有4種:DOM、SAX、JDOM、JAXB
1.  DOM(Document Object Model)
 此方法主要由W3C提供,它將xml檔案全部讀入記憶體中,然後將各個元素組成一棵資料樹,以便快速的訪問各個節點 。 因此非常消耗系統效能 ,對比較大的文檔不適宜採用DOM方法來解析。 DOM API 直接沿襲了 XML 規範。每個結點都可以擴充的基於 Node 的介面,就多態性的觀點來講,它是優秀的,但是在 Java 語言中的應用不方便,並且可讀性不強。
 執行個體:
import javax.xml.parsers.*;
//XML解析器介面
import org.w3c.dom.*;
//XML的DOM實現
import org.apache.crimson.tree.XmlDocument;
//寫XML檔案要用到

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 //允許名字空間
 factory.setNamespaceAware(true);
 //允許驗證
 factory.setValidating(true);
 //獲得DocumentBuilder的一個執行個體
try {
 DocumentBuilder builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException pce) {
System.err.println(pce);
//  出異常時輸出異常資訊,然後退出,下同
System.exit(1);
}
//解析文檔,並獲得一個Document執行個體。
try {
Document doc = builder.parse(fileURI);
} catch (DOMException dom) {
System.err.println(dom.getMessage());
System.exit(1);
} catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);     
}

//獲得根節點StuInfo
Element elmtStuInfo = doc.getDocumentElement();

//得到所有student節點
 NodeList nlStudent = elmtStuInfo.getElementsByTagNameNS(
                                       strNamespace, "student");
for (……){
     //當前student節點元素
     Element elmtStudent = (Element)nlStudent.item(i);

     NodeList nlCurrent =              elmtStudent.getElementsByTagNameNS(
                                     strNamespace, "name");
}

對於讀取得方法其實是很簡單的,寫入xml檔案也是一樣不複雜。

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory .newDocumentBuilder();
} catch (ParserConfigurationException pce) {
System.err.println(pce);
System.exit(1);
}

Document doc = null;
doc = builder .newDocument();

//下面是建立XML文檔內容的過程,
//先建立根項目"學生花名冊"
Element root = doc.createElement("學生花名冊");
//根項目添加上文檔
doc.appendChild(root);
//建立"學生"元素,添加到根項目
Element student = doc.createElement("學生");
student.setAttribute("性別", studentBean.getSex());
root.appendChild(student);
//建立"姓名"元素,添加到學生下面,下同
Element name = doc.createElement("姓名");
student.appendChild(name);
Text tName = doc.createTextNode(studentBean.getName());
name.appendChild(tName);

Element age = doc.createElement("年齡");
student.appendChild(age);
Text tAge = doc.createTextNode(String.valueOf(studentBean.getAge()));
age.appendChild(tAge);

2.SAX (Simple API for XML)
 此方法主要由XML-DEV 郵件清單的成員開發的,SAX是基於事件的方法,它很類似於標籤庫的處理機制,在標籤開始、結束以及錯誤發生等等地方調用相應的介面實現方法,不是全部文檔都讀入記憶體。 SAX具有優異的效能和利用更少的儲存空間特點。SAX 的設計只考慮了功能的強大性,卻沒有考慮程式員使用起來是否方便。

使用必須擴充ContentHandler、ErrorHandler、DTDHandler等,但是必須擴充ContentHandler(或者DefaultHandler )。

import org.xml.sax.*;

public  class  MyContentHandler implements ContentHandler {
  … …
}

/**
     * 當其他某一個呼叫事件發生時,先調用此方法來在文檔中定位。
     * @param locator
     */
    public void setDocumentLocator(Locator locator){

    }
/**
     * 在解析整個文檔開始時調用
     * @throws SAXException
     */
    public void startDocument() throws SAXException{
        System.out.println("** Student information start **");
    }
/**
     * 在解析整個文檔結束時調用
     * @throws SAXException
     */
    public void endDocument() throws SAXException{
        System.out.println("**** Student information end ****");
    }

/**
     * 在解析名字空間開始時調用
     * @param prefix
     * @param uri
     * @throws SAXException
     */
    public void startPrefixMapping(String prefix
        , String uri) throws SAXException{
    }
/**
     * 在解析名字空間結束時調用
     * @param prefix
     * @throws SAXException
     */
    public void endPrefixMapping(String prefix) throws SAXException{
    }
/**
     * 在解析元素開始時調用
     * @param namespaceURI
     * @param localName
     * @param qName
     * @param atts
     * @throws SAXException
     */
    public void startElement(String namespaceURI, String localName
        , String qName, Attributes atts) throws SAXException{
    }
/** 在解析元素結束時調用
     * @param namespaceURI
     * @param localName 本地名,如student
     * @param qName 原始名,如LIT:student
     * @throws SAXException   */
    public void endElement(String namespaceURI, String localName,String qName) throws SAXException{
  if (localName.equals(“student”)){
            System.out.println(localName+":"+currentData);
        }
}
取得元素資料的方法——characters
取得元素資料中的空白的方法——ignorableWhitespace
在解析到處理指示時調用的方法——processingInstruction
當未驗證解析器忽略實體時調用的方法——skippedEntity
運行時,只需要使用下列代碼:

MySAXParser mySAXParser = new MySAXParser();

mySAXParser.parserXMLFile("SutInfo.xml");

3.JDOM

 JDOM的處理方式有些類似於DOM,但它主要是用SAX實現的 。JDOM用Java的資料類型來定義操作資料樹的各個節點 。JDOM的效能也很優越。

import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;

SAXBuilder builder = new SAXBuilder(false);
//得到Document
Document doc = builder.build(fileURI);
//名字空間
Namespace ns = Namespace.getNamespace("LIT"
                           , "http://www.lit.edu.cn/student/");

//取得所有LIT:student節點的集合
List lstStudents = elmtStuInfo.getChildren("student",                                                                                                   ns);

for ( … ){
 Element elmtStudent = (Element)lstStudents.get(i);
 elmtStudent.getChildTextTrim("name", ns);
}
//修改
elmtLesson.getChild("lessonScore" , ns).setText("100");
//刪除
elmtStuInfo.removeChild("master", ns);
//添加
elmtStuInfo.addContent(new Element("master" , ns).addContent(new Entity("masterName")));
//輸出文檔
//第一個參數是縮排字串,這裡是4個空格。
//第二個參數是true,表示需要換行。
XMLOutputter printDoc = new XMLOutputter(" ", true);
 printDoc.output(doc, new FileOutputStream("StuInfo.xml"));

4.JAXB (Java And XML Binding)

 JAXB 是以SUN為主的一些公司公布的。JAXB將schema(或者DTD)映射為java對象(.java檔案),然後使用這些java對象來解析xml檔案。需要使用之前產生java檔案,因而要有固定的schema,無法處理動態xml檔案。

首先使用xjc命令,產生java檔案
  xjc  [-options ...]

(產生的檔案較多)
JAXBContext jc = JAXBContext.newInstance(“packageName");

 Unmarshaller unmarshaller = jc.createUnmarshaller();

Collection collection= (Collection)unmarshaller.unmarshal(new File( "books.xml"));
CollectionType.BooksType booksType =collection.getBooks();
List bookList = booksType.getBook();
for( … ){
 test.jaxb.BookType book =(test.jaxb.BookType) bookList.get(i);
 System.out.println("Book Name: " + book.getName().trim());
   System.out.println("Book ISBN: " +  book.getISBN());
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.