JAVA操作XML的完整例子——W3C DOM篇__JAVA

來源:互聯網
上載者:User

這是一個用JAVA W3C DOM 進行XML操作的例子,包含了查詢、增加、修改、刪除、儲存的基本操作。較完整的描述了一個XML的整個操作流程。適合剛入門JAVA XML操作的朋友參考和學習。

假設有XML檔案:test1.xml <? xml version="1.0" encoding="UTF-8" ?>
< books >
  < book >
   < name > 哈裡傳輸速率 </ name >
   < price > 10 </ price >
   < memo > 這是一本很好看的書。 </ memo >
  </ book >
  < book  id ="B02" >
   < name > 三國演義 </ name >
   < price > 10 </ price >
   < memo > 四大名著之一。 </ memo >
  </ book >
  < book  id ="B03" >
   < name > 水滸 </ name >
   < price > 6 </ price >
   < memo > 四大名著之一。 </ memo >
  </ book >
  < book  id ="B04" >
   < name > 紅樓 </ name >
   < price > 5 </ price >
   < memo > 四大名著之一。 </ memo >
  </ book >
</ books >   

 

下面是為Test.java import  java.io.File;
import  java.io.FileNotFoundException;
import  java.io.FileOutputStream;
import  java.io.IOException;

import  org.w3c.dom. * ;
import  org.xml.sax.SAXException;

import  javax.xml.parsers. * ;
import  javax.xml.transform. * ;
import  javax.xml.transform.dom.DOMSource;
import  javax.xml.transform.stream. * ;
import  javax.xml.xpath. * ;

public   class  Test  ... {
    public static void main(String[] args) ...{
        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
        Element theBook=null, theElem=null, root=null;
        try ...{
            factory.setIgnoringElementContentWhitespace(true);
            
            DocumentBuilder db=factory.newDocumentBuilder();
            Document xmldoc=db.parse(new File("Test1.xml"));
            root=xmldoc.getDocumentElement();
            
            //---  建立一本書開始 ----
            theBook=xmldoc.createElement("book");
            theElem=xmldoc.createElement("name");
            theElem.setTextContent("新書");
            theBook.appendChild(theElem);
            
            theElem=xmldoc.createElement("price");
            theElem.setTextContent("20");
            theBook.appendChild(theElem);

            theElem=xmldoc.createElement("memo");
            theElem.setTextContent("新書的更好看。");
            theBook.appendChild(theElem);
            root.appendChild(theBook);
            System.out.println("---  建立一本書開始 ----");

聯繫我們

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