阅读更多
dom : document object model 文档对象模型
java dom就是基于w3c dom规范的一套实现,面向接口编程。
1. class diagram
其中: entittyresolver 和 errorhandler 来自于 sax api
2. 实例
domtest.java
package com.siyuan.xml;
import java.io.ioexception;
import javax.xml.parsers.documentbuilder;
import javax.xml.parsers.documentbuilderfactory;
import javax.xml.parsers.parserconfigurationexception;
import javax.xml.transform.source;
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.attr;
import org.w3c.dom.document;
import org.w3c.dom.element;
import org.w3c.dom.namednodemap;
import org.w3c.dom.node;
import org.w3c.dom.nodelist;
import org.w3c.dom.text;
import org.xml.sax.saxexception;
import org.xml.sax.helpers.defaulthandler;
public class domtest {
public static void printelement(element e) {
system.out.println("element : " + e.getnodename() + "---------------");
namednodemap attrs = e.getattributes();
for (int i = 0; i < attrs.getlength(); i++) {
attr attr = (attr) attrs.item(i);
system.out.println("attribute[" + i + "] : " + attr.getname() + "=" + attr.getvalue());
}
nodelist children = e.getchildnodes();
for (int i = 0; i < children.getlength(); i++) {
node node = children.item(i);
if (node instanceof text) {
system.out.println("text node : " + ((text) node).getwholetext());
} else {
printelement((element) children.item(i));
}
}
}
/**
* @param args
* @throws parserconfigurationexception
* @throws ioexception
* @throws saxexception
* @throws transformerexception
*/
public static void main(string[] args) throws parserconfigurationexception, saxexception, ioexception, transformerexception {
// todo auto-generated method stub
documentbuilderfactory factory = documentbuilderfactory.newinstance();
documentbuilder builder = factory.newdocumentbuilder();
defaulthandler handler = new workershandler();
builder.setentityresolver(handler);
builder.seterrorhandler(handler);
document document = builder.parse("src/com/siyuan/xml/workers.xml");
printelement(document.getdocumentelement());
transformerfactory transformerfactory = transformerfactory.newinstance();
transformer transformer = transformerfactory.newtransformer();
transformer.transform(new domsource(document.getdocumentelement()), new streamresult("src/com/siyuan/xml/workers1.xml"));
}
}