JAVA操作XML實(shí)例分析
本文實(shí)例講述了JAVA操作XML的方法。分享給大家供大家參考。具體如下:
java代碼如下:
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("--- 查詢(xún)找《哈里波特》 ----");
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)==================");
//--- 新建一本書(shū)開(kāi)始 ----
theBook=xmldoc.createElement("book");
theElem=xmldoc.createElement("name");
theElem.setTextContent("新書(shū)");
theBook.appendChild(theElem);
theElem=xmldoc.createElement("price");
theElem.setTextContent("20");
theBook.appendChild(theElem);
theElem=xmldoc.createElement("memo");
theElem.setTextContent("新書(shū)的更好看。");
theBook.appendChild(theElem);
root.appendChild(theBook);
System.out.println("--- 新建一本書(shū)開(kāi)始 ----");
output(xmldoc);
System.out.println("==============================");
//--- 新建一本書(shū)完成 ----
//--- 下面對(duì)《哈里波特》做一些修改。 ----
//--- 查詢(xún)找《哈里波特》----
//--- 此時(shí)修改這本書(shū)的價(jià)格 -----
theBook.getElementsByTagName("price").item(0).setTextContent("15");//getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,getElementsByTagName("price")相當(dāng)于xpath的".//price"。
System.out.println("--- 此時(shí)修改這本書(shū)的價(jià)格 ----");
output(theBook);
//--- 另外還想加一個(gè)屬性id,值為B01 ----
theBook.setAttribute("id", "B01");
System.out.println("--- 另外還想加一個(gè)屬性id,值為B01 ----");
output(theBook);
//--- 對(duì)《哈里波特》修改完成。 ----
//--- 要用id屬性刪除《三國(guó)演義》這本書(shū) ----
theBook=(Element) selectSingleNode("/books/book[@id='B02']", root);
System.out.println("--- 要用id屬性刪除《三國(guó)演義》這本書(shū) ----");
output(theBook);
theBook.getParentNode().removeChild(theBook);
System.out.println("--- 刪除后的XML ----");
output(xmldoc);
//--- 再將所有價(jià)格低于10的書(shū)刪除 ----
NodeList someBooks=selectNodes("/books/book[price<10]", root);
System.out.println("--- 再將所有價(jià)格低于10的書(shū)刪除 ---");
System.out.println("--- 符合條件的書(shū)有 "+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字符串輸出到控制臺(tái)
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) {//查找節(jié)點(diǎn),并返回第一個(gè)符合條件節(jié)點(diǎn)
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) {//查找節(jié)點(diǎn),返回符合條件的節(jié)點(diǎn)集。
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文件如下:
<books>
<book>
<name>哈里波特</name>
<price>10</price>
<memo>這是一本很好看的書(shū)。</memo>
</book>
<book id="B02">
<name>三國(guó)演義</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>
希望本文所述對(duì)大家的java程序設(shè)計(jì)有所幫助。
相關(guān)文章
優(yōu)化spring?boot應(yīng)用后6s內(nèi)啟動(dòng)內(nèi)存減半
這篇文章主要為大家介紹了優(yōu)化spring?boot后應(yīng)用6s內(nèi)啟動(dòng)內(nèi)存減半的優(yōu)化示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2022-02-02
解決mybatis用Map返回的字段全變大寫(xiě)的問(wèn)題
這篇文章主要介紹了解決mybatis用Map返回的字段全變大寫(xiě)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-12-12
springboot實(shí)現(xiàn)登錄功能的完整步驟
這篇文章主要給大家介紹了關(guān)于springboot實(shí)現(xiàn)登錄功能的完整步驟,在web應(yīng)用程序中,用戶(hù)登錄權(quán)限驗(yàn)證是非常重要的一個(gè)步驟,文中通過(guò)代碼以及圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-09-09
Spring細(xì)數(shù)兩種代理模式之靜態(tài)代理和動(dòng)態(tài)代理概念及使用
代理是一種設(shè)計(jì)模式,提供了對(duì)目標(biāo)對(duì)象另外的訪問(wèn)方式,即通過(guò)代理對(duì)象訪問(wèn)目標(biāo)對(duì)象??梢圆恍薷哪繕?biāo)對(duì)象,對(duì)目標(biāo)對(duì)象功能進(jìn)行拓展。在我們學(xué)習(xí)Spring的時(shí)候就會(huì)發(fā)現(xiàn),AOP(面向切面編程)的底層就是代理2023-02-02
Mybatis攔截器注解@Intercepts與@Signature注解使用
本文主要介紹了Mybatis攔截器注解@Intercepts與@Signature注解使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-07-07
Java實(shí)現(xiàn)兩人五子棋游戲(七) 屏幕提示信息
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)兩人五子棋游戲,屏幕提示游戲信息,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03
Java讀取文件的簡(jiǎn)單實(shí)現(xiàn)方法
這篇文章主要介紹了Java讀取文件的簡(jiǎn)單實(shí)現(xiàn)方法,通過(guò)一個(gè)讀取txt格式的log文件為例,詳細(xì)的講述了Java讀取文件的方法及原理,需要的朋友可以參考下2014-09-09
詳解Java模擬棧的實(shí)現(xiàn)以及Stack類(lèi)的介紹
棧是一種數(shù)據(jù)結(jié)構(gòu),它按照后進(jìn)先出的原則來(lái)存儲(chǔ)和訪問(wèn)數(shù)據(jù)。Stack是一個(gè)類(lèi),表示棧數(shù)據(jù)結(jié)構(gòu)的實(shí)現(xiàn)。本文就來(lái)和大家介紹一下Java模擬棧的實(shí)現(xiàn)以及Stack類(lèi)的使用,需要的可以參考一下2023-04-04

