<?xml version="1.0" encoding="UTF-8"?>
<PhoneInfo>
<Brand name="華爲">
<type name="U8650"/>
<type name="HW123"/>
<type name="HW456"/>
</Brand>
<Brand name="蘋果">
<type name="iphone6"/>
<type name="iphone6p"/>
<type name="iphone7"/>
</Brand>
</PhoneInfo>
package cn.dom;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
*使用DOM解析文件
*/
public class ParseXMLDemo {
//收藏信息.xml對應的Document
private Document document;
public void getDom(){
//獲得工廠解析器
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
try {
//根據解析器工廠獲得解析器
DocumentBuilder builder=factory.newDocumentBuilder();
//解析器來解析XML文件獲得Document對象,一個路徑下的文件
document=builder.parse("收藏信息.xml");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 獲取手機品牌相關信息
*/
public void showInfo(){
//以Document做起點,先拿到所有Brand節點
NodeList brands=document.getElementsByTagName("Brand");
//遍歷brands,從中拿出每一個brand節點
//新方法,getLength()
for (int i = 0; i < brands.getLength(); i++) {
Node node=brands.item(i);
Element eleBrand=(Element) node;
//拿到屬於brand的name
System.out.println(eleBrand.getAttribute("name"));
//繼續往下,找每個Brand的子節點
NodeList types=eleBrand.getChildNodes();
for (int j = 0; j < types.getLength(); j++) {
Node typeNode=types.item(j);
//判斷該子節點是否爲元素節點
//Node.ELEMENT_NODE是否爲元素
if(typeNode.getNodeType()==Node.ELEMENT_NODE){
Element eleType=(Element) typeNode;
System.out.println("\t"+eleType.getAttribute("name"));
}
}
}
}
/**
* 爲XML文件添加元素
*/
public void addEle(){
//(1)創建<Brand name="三星">
Element brand=document.createElement("Brand");
//爲<Brand>設置name屬性取值爲三星
brand.setAttribute("name", "三星");
//<Type name="NOTE2"/>
Element type = document.createElement("Type");
type.setAttribute("name", "NOTE2");
//將type作爲Brand的子元素
brand.appendChild(type);
//將Brand放到PhoneInfo中去,位置爲第一個PhoneInfo,item(0)
document.getElementsByTagName("PhoneInfo").item(0).appendChild(brand);
saveXML("收藏信息.xml");
}
/**
* 保存XML文件(需藉助轉換器:源(最新DOM樹)--》目的地(收藏信息.xml),藉助輸出流來實現)
*/
public void saveXML(String path){
//轉換器工廠
TransformerFactory factory=TransformerFactory.newInstance();
//設置格式,首行縮進4個空格
factory.setAttribute("indent-number", 4);
try {
//轉換器
Transformer transformer=factory.newTransformer();
//指定轉換格式,ENCODING文字編碼格式
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
//設置准許縮進YES
transformer.setOutputProperty(OutputKeys.INDENT, "YES");
//源(最新DOM樹)-->目的地(收藏信息.xml)
DOMSource source=new DOMSource(document);
//傳進一個要保存的文件地址path
OutputStream out=new FileOutputStream(path);
StreamResult result=new StreamResult(new OutputStreamWriter(out,"UTF-8"));
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 修改元素
* 給Brand添加id屬性 值爲下標+""一個空字符,String類型
*/
public void updateEle(){
//獲得所有元素
NodeList brands=document.getElementsByTagName("Brand");
for (int i = 0; i < brands.getLength(); i++) {
Node brand=brands.item(i);
Element brandEle=(Element) brand;
brandEle.setAttribute("id", i+"");
}
saveXML("收藏信息.xml");
}
/**
* 刪除華爲手機
*/
public void deleteEle(){
NodeList brands=document.getElementsByTagName("Brand");
for (int i = 0; i < brands.getLength(); i++) {
Node brand=brands.item(i);
Element brandEle=(Element) brand;
if(brandEle.getAttribute("name").equals("華爲")){
//用父類節點刪除子節點
brandEle.getParentNode().removeChild(brandEle);
}
}
saveXML("收藏信息.xml");
}
}
package cn.dom;
public class Test {
public static void main(String[] args) {
ParseXMLDemo pd=new ParseXMLDemo();
pd.getDom();
//pd.addEle();
//pd.updateEle();
pd.deleteEle();
pd.showInfo();
}
}
Element:XML文檔中的一個元素 | String getTagName | 獲取元素名稱 |
常用接口 | 常用方法 | 說明 |
Document:表示整個XML文檔 | NodeList getElementsByTagName(String Tag) | 按文檔順序返回文檔中指定標記名稱的所有元素集合 |
Element createElement(String tagName) | 創建指定標記名稱的元素 | |
Node:該文檔樹中的單個節點 | NodeList getChildNodes() | 獲取該元素所有子節點,返回節點集合 |