一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務器之家 - 編程語言 - JAVA教程 - JAVA操作XML實例分析

JAVA操作XML實例分析

2019-12-12 15:07瘋狂的流浪 JAVA教程

這篇文章主要介紹了JAVA操作XML的方法,實例分析了java操作XML文件的常用技巧,需要的朋友可以參考下

本文實例講述了JAVA操作XML的方法。分享給大家供大家參考。具體如下:

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=(Element) selectSingleNode("/books/book[name='哈里波特']", root);
            System.out.println("--- 查詢找《哈里波特》 ----");
            Element nameNode=(Element)theBook.getElementsByTagName("price").item(0); 
            String name=nameNode.getFirstChild().getNodeValue(); 
            System.out.println(name);
            output(theBook);
            System.out.println("=============selectSingleNode(books/book[name='哈里波特'], root)==================");
            //--- 新建一本書開始 ----
            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("--- 新建一本書開始 ----");
            output(xmldoc);
            System.out.println("==============================");
            //--- 新建一本書完成 ----
            //--- 下面對《哈里波特》做一些修改。 ----
            //--- 查詢找《哈里波特》----
            //--- 此時修改這本書的價格 -----
            theBook.getElementsByTagName("price").item(0).setTextContent("15");//getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,getElementsByTagName("price")相當于xpath的".//price"。
            System.out.println("--- 此時修改這本書的價格 ----");
            output(theBook);
            //--- 另外還想加一個屬性id,值為B01 ----
            theBook.setAttribute("id", "B01");
            System.out.println("--- 另外還想加一個屬性id,值為B01 ----");
            output(theBook);
            //--- 對《哈里波特》修改完成。 ----
            //--- 要用id屬性刪除《三國演義》這本書 ----
            theBook=(Element) selectSingleNode("/books/book[@id='B02']", root);
            System.out.println("--- 要用id屬性刪除《三國演義》這本書 ----");
            output(theBook);
            theBook.getParentNode().removeChild(theBook);
            System.out.println("--- 刪除后的XML ----");
            output(xmldoc);
            //--- 再將所有價格低于10的書刪除 ----
            NodeList someBooks=selectNodes("/books/book[price<10]", root);
            System.out.println("--- 再將所有價格低于10的書刪除 ---");
            System.out.println("--- 符合條件的書有 "+someBooks.getLength()+"本。 ---");
            for(int i=0;i<someBooks.getLength();i++) {
                someBooks.item(i).getParentNode().removeChild(someBooks.item(i));
            }
            output(xmldoc);
            saveXml("Test1_Edited.xml", xmldoc);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void output(Node node) {//將node的XML字符串輸出到控制臺
        TransformerFactory transFactory=TransformerFactory.newInstance();
        try {
            Transformer transformer = transFactory.newTransformer();
            transformer.setOutputProperty("encoding", "gb2312");
            transformer.setOutputProperty("indent", "yes");
            DOMSource source=new DOMSource();
            source.setNode(node);
            StreamResult result=new StreamResult();
            result.setOutputStream(System.out);
            transformer.transform(source, result);
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }   
    }
    public static Node selectSingleNode(String express, Object source) {//查找節點,并返回第一個符合條件節點
        Node result=null;
        XPathFactory xpathFactory=XPathFactory.newInstance();
        XPath xpath=xpathFactory.newXPath();
        try {
            result=(Node) xpath.evaluate(express, source, XPathConstants.NODE);
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        return result;
    }
    public static NodeList selectNodes(String express, Object source) {//查找節點,返回符合條件的節點集。
        NodeList result=null;
        XPathFactory xpathFactory=XPathFactory.newInstance();
        XPath xpath=xpathFactory.newXPath();
        try {
            result=(NodeList) xpath.evaluate(express, source, XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        return result;
    }
    public static void saveXml(String fileName, Document doc) {//將Document輸出到文件
        TransformerFactory transFactory=TransformerFactory.newInstance();
        try {
            Transformer transformer = transFactory.newTransformer();
            transformer.setOutputProperty("indent", "yes");
            DOMSource source=new DOMSource();
            source.setNode(doc);
            StreamResult result=new StreamResult();
            result.setOutputStream(new FileOutputStream(fileName));
            transformer.transform(source, result);
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }   
    }
}


  
XML文件如下:

復制代碼代碼如下:
<?xml version="1.0" encoding="GBK"?>
<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>

 

希望本文所述對大家的java程序設計有所幫助。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 色欲麻豆国产福利精品 | 91久久夜色精品国产九色 | 男人天堂官方网站 | 97影院伦理 | 99久久精品自在自看国产 | 欧美日韩视频在线第一区二区三区 | 精品在线免费播放 | 午夜影院网页 | 激情视频在线播放 | 日韩免费视频播放 | dasd-698黑人在线播放 | 日本老妇人乱视频 | 大乳奶水bbw | 99这里只有精品视频 | 国产第一综合另类色区奇米 | 精品一久久香蕉国产线看播放 | 痴mu动漫成年动漫在线观看 | 91麻豆精东果冻天美传媒老狼 | 国产日韩欧美 | 毛片网站大全 | 亚洲精品国产一区二区在线 | 91污无限制破解安卓2021 | 青青草原免费在线视频 | 国产成人亚洲精品91专区高清 | 亚洲人成激情在线播放 | 久热人人综合人人九九精品视频 | 国产人妖ts在线视频网 | 久久精品国产在热亚洲完整版 | 国产老肥熟xxxx | 3d动漫美女被吸乳羞羞视频 | 日本手机在线视频 | 十六一下岁女子毛片免费 | 无套啪啪| 国产精品福利短视在线播放频 | 国内精品一区二区在线观看 | 8天堂资源在线官网 | 国产亚洲精aa在线观看香蕉 | 国产欧美精品一区二区三区–老狼 | 国产精品成人一区二区 | 故意短裙公车被强好爽在线播放 | 久久伊人精品青青草原2021 |