public static Document getDocument() throws Exception{
//1.創建工廠
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
//2.得到dom解析器
DocumentBuilder builder=factory.newDocumentBuilder();
//3.解析xml文檔,得到document
return builder.parse(filename);//filename 為解析的xml文檔路徑
}
<?xml version="1.0" encoding="UTF-8" standalone="no"?><書架>
<書>
<書名 name = “xxx”>Java就業培訓教程</書名>
<作者>張孝祥</作者>
<售價>59.00元</售價>
</書>
<書>
<書名>JavaScript網頁開發</書名>
<作者>張孝祥</作者>
<售價>28.00元</售價>
</書>
</書架>
NodeList list=document.getElementsByTagName("書名");
Node node= list.item(1);
String content=node.getTextContent();
System.out.println(content);
Node root = document.getElementsByTagName("書架").item(0);//得到根節點
list(root);
private void list(Node node) {
if(node instanceof Element ){
System.out.println(node.getNodeName());
}
NodeList list = node.getChildNodes();
for(int i=0;i<list.getLength();i++){
Node child = list.item(i);
list(child);
}
}
Element bookname=(Element) document.getElementsByTagName("書名").item(0);
String value=bookname.getAttribute("name");
System.out.println(value);
//創建節點
Element price = document.createElement("售價");
price.setTextContent("59.00元");
//創建節點掛載第一本書
Element book =(Element) document.getElementsByTagName("書").item(0);
book.appendChild(price);
//把更新的數據寫回文檔中
TransformerFactory tffactory=TransformerFactory.newInstance();
Transformer tf=tffactory.newTransformer();
tf.transform(new DOMSource(document), new StreamResult(new FileOutputStream(filename)));
//創建節點
Element price = document.createElement("售價");
price.setTextContent("59.00元");
//得到參考節點
Element refNode=(Element) document.getElementsByTagName("售價").item(0);
//得到掛載的節點
Element book =(Element) document.getElementsByTagName("書").item(0);
//往book節點的指定位置插入
book.insertBefore(price, refNode);
//把更新的數據寫回文檔中
TransformerFactory tffactory=TransformerFactory.newInstance();
Transformer tf=tffactory.newTransformer();
tf.transform(new DOMSource(document), new StreamResult(new FileOutputStream(filename)));
Element bookname=(Element) document.getElementsByTagName("書名").item(0);
bookname.setAttribute("name", "xxxxxx");
//得到要刪除的節點
Element element=(Element) document.getElementsByTagName("售價").item(0);
element.getParentNode().removeChild(element);
//把更新的數據寫回文檔中
TransformerFactory tffactory=TransformerFactory.newInstance();
Transformer tf=tffactory.newTransformer();
tf.transform(new DOMSource(document), new StreamResult(new FileOutputStream(filename)));