【计算机论文全套栏目提醒】:本文主要为网学会员提供“JAVA操作XML的完整例子——W3C DOM篇 - 计算机理论”,希望对需要JAVA操作XML的完整例子——W3C DOM篇 - 计算机理论网友有所帮助,学习一下!
//JAVA操作XML的完整例子——W3C DOM篇 哈里波特10 这是一本很好看的书。
三国演义10 四大名著之一。
水浒6 四大名著之一。
红楼5 四大名著之一。
import java.io.Fileimport java.io.FileNotFoundExceptionimport java.io.FileOutputStreamimport java.io.IOExceptionimport org.w3c.dom.import org.xml.sax.SAXExceptionimport javax.xml.parsers.import javax.xml.transform.import javax.xml.transform.dom.DOMSourceimport javax.xml.transform.stream.import javax.xml.xpath.public class Test ... public static void mainString args ... DocumentBuilderFactory factoryDocumentBuilderFactory.newInstance Element theBooknull theElemnull rootnull try ... factory.setIgnoringElementContentWhitespacetrue DocumentBuilder dbfactory.newDocumentBuilder Document xmldocdb.parsenew FileTest1.xml rootxmldoc.getDocumentElement //--- 新建一本书开始 ---- theBookxmldoc.createElementbook theElemxmldoc.createElementname theElem.setTextContent新书 theBook.appendChildtheElem theElemxmldoc.createElementprice theElem.setTextContent20 theBook.appendChildtheElem theElemxmldoc.createElementmemo theElem.setTextContent新书的更好看。
theBook.appendChildtheElem root.appendChildtheBook System.out.println--- 新建一本书开始 ---- outputxmldoc //--- 新建一本书完成 ---- //--- 下面对《哈里波特》做一些修改。
---- //--- 查询找《哈里波特》---- theBookElement selectSingleNode/books/bookname哈里波特 root System.out.println--- 查询找《哈里波特》 ---- outputtheBook //--- 此时修改这本书的价格 ----- theBook.getElementsByTagNameprice.item0.setTextContent15//getElementsByTagName返回的是NodeList,所以要跟上item0 System.out.println--- 此时修改这本书的价格 ---- outputtheBook //--- 另外还想加一个属性id,值为B01 ---- theBook.setAttributeid B01 System.out.println--- 另外还想加一个属性id,值为B01 ---- outputtheBook //--- 对《哈里波特》修改完成。
---- //--- 要用id属性删除《三国演义》这本书 ---- theBookElement selectSingleNode/books/bookidB02 root System.out.println--- 要用id属性删除《三国演义》这本书 ---- outputtheBook theBook.getParentNode.removeChildtheBook System.out.println--- 删除后的XML ---- outputxmldoc //--- 再将所有价格低于10的书删除 ---- NodeList someBooksselectNodes/books/bookprice