| |
Java的DOM编辑:创建一个新的DOM解析树 |
|
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class DOMNew {
static public void main(String[] arg) {
if (arg.length != 1) {
System.err.println("Usage: DOMNew <outfile>");
System.exit(1);
}
DOMNew dc = new DOMNew();
dc.createNew(arg[0]);
}
public void createNew(String outfile) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
dbf.setNamespaceAware(true);
dbf.setIgnoringElementContentWhitespace(true);
Document doc = null;
try {
DocumentBuilder builder = dbf.newDocumentBuilder();
doc = builder.newDocument();
buildTree(doc);
FileOutputStream fos = new FileOutputStream(outfile);
TreeToXML ttxml = new TreeToXML();
ttxml.write(fos, doc);
fos.close();
} catch (ParserConfigurationException e) {
System.err.println(e);
System.exit(1);
} catch (IOException e) {
System.err.println(e);
System.exit(1);
}
}
public void buildTree(Document doc) {
Element name;
Text text;
Element root = doc.createElement("places");
doc.appendChild(root);
name = doc.createElement("name");
text = doc.createTextNode("Algonquin Roundtable");
name.appendChild(text);
root.appendChild(name);
name = doc.createElement("name");
text = doc.createTextNode("Bayou Teche");
name.appendChild(text);
root.appendChild(name);
}
}
|
|
|
Related examples in the same category |
|