?? add_delxml.java
字號(hào):
import javax.xml.parsers.*;
import org.xml.sax.*;
import java.io.*;
import org.w3c.dom.*;
public class Add_DelXML
{
// 聲明XML文件
static Document document;
public static void main(String[] args) throws Exception
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// 設(shè)定解析的叁數(shù)
dbf.setIgnoringComments(true);
dbf.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = dbf.newDocumentBuilder();
// 建立新XML文件
document = db.newDocument();
// 建立根元素
Element root = (Element) document.createElement("book");
document.appendChild(root);
// 新增子元素price
Element temp = (Element) document.createElement("price");
root.appendChild(temp);
temp.appendChild(document.createTextNode("38"));
// 新增子元素title
temp = (Element) document.createElement("title");
root.appendChild(temp);
temp.appendChild(document.createTextNode("JSP動(dòng)態(tài)網(wǎng)頁(yè)設(shè)計(jì)"));
// 新增author元素
Element newNode = (Element) document.createElement("author");
root.insertBefore(newNode, root.getFirstChild());
Node newText = document.createTextNode("王五");
root.getFirstChild().appendChild(newText);
// 新增屬性
temp = (Element) root.getElementsByTagName("price").item(0);
temp.setAttribute("sale","Y");
System.out.println("建立的XML文件: ");
printXML(root);
// 刪除author元素
root.removeChild((Element) root.getElementsByTagName("author").item(0));
// 刪除price屬性sale
Element delNode=(Element) root.getElementsByTagName("price").item(0);
delNode.removeAttribute("sale");
System.out.println("\n刪除后的XML文件: ");
printXML(root);
}
private static void printXML(Node root)
{
// 顯示XML文件
System.out.println("根元素: " + root.getNodeName());
NodeList nodes = root.getChildNodes();
// 獲取所有的子節(jié)點(diǎn)
for (int i=0; i < nodes.getLength(); i++)
{
// 元素和文字節(jié)點(diǎn)
System.out.print("元素: " + nodes.item(i).getNodeName());
System.out.println("/" + nodes.item(i).getFirstChild().getNodeValue());
// 顯示指定元素的屬性值
if (nodes.item(i).hasAttributes()) {
NamedNodeMap atts = nodes.item(i).getAttributes();
for (int j = 0; j < atts.getLength(); j++)
{
Node att = atts.item(j);
System.out.print(" +-- " + att.getNodeName());
System.out.println("/" + att.getNodeValue());
}
}
}
}
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -