import java.io.*;
import org.w3c.dom.*;
import org.w3c.dom.Node;
import org.xml.sax.*;
import javax.xml.parsers.*;
public class Homework
{
public void create(Document doc)
{
Element root = doc.createElement("Catalog");
Element eProd = doc.createElement("products");
Element eId = doc.createElement("prod_id");
Element eName = doc.createElement("prod_name");
Element ePrice = doc.createElement("price");
Text tId = doc.createTextNode("a001");
Text tName = doc.createTextNode("实例");
Text tPrice = doc.createTextNode("100");
eProd.appendChild(eId).appendChild(tId);
eProd.appendChild(eName).appendChild(tName);
eProd.appendChild(ePrice).appendChild(tPrice);
doc.appendChild(root).appendChild(eProd);
}
public void append(Document doc,Node e)
{
e.appendChild(doc.createElement("appendElement"));
}
public void insert(Document doc,Node e)
{
e.insertBefore(doc.createElement("insertElement"),e.getFirstChild());
}
public void replace(Document doc,Node e)
{
e.replaceChild(doc.createElement("replaceElement"),e.getLastChild());
}
public void remove(Document doc,Node e)
{
e.removeChild(e.getLastChild());
}
public void printDOC(Document doc)
{
NodeList nl = doc.getElementsByTagName("*");
Element e;
int len;
len = nl.getLength();
for (int j=0;j < len;j++)
{
e = (Element)nl.item(j);
System.out.print(e.getTagName()+":");
if (e.hasChildNodes())
System.out.print(e.getFirstChild().getNodeValue());
}
System.out.println();
}
static public void main(String[] argv)
{
try
{
DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder domparser = dbfactory.newDocumentBuilder();
Document doc = domparser.newDocument();
Homework hw = new Homework();
hw.create(doc);
hw.append(doc,doc.getDocumentElement()); //测试
hw.insert(doc,doc.getDocumentElement().getFirstChild()); //测试
hw.replace(doc,doc.getDocumentElement().getFirstChild()); //测试
hw.remove(doc,doc.getDocumentElement().getFirstChild()); //测试
hw.printDOC(doc);
}
catch (ParserConfigurationException p)
{
System.out.println(p.toString());
}
}
}