中科院云平台架构师,专注于数字化、智能化,技术方向:云、Linux内核、AI、MES/ERP/CRM/OA、物联网、传感器、大数据、ML、微服务。
分类: Java
2013-04-27 15:38:18
这个是最原始,最古老的方法。仅适用于配置文件解析,数据文件就别用它了。受不了的。
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
public class DOMTest {
private static String inFile = "c:\\people.xml";
private String outFile = "c:\\people.xml";
public static void main(String args[]) {
System.out.println("**********Start****************");
DOMTest domTest = new DOMTest();
//domTest.createDOM();
domTest.readDom(inFile);
System.out.println("**********End****************");
}
public void createDOM() {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.newDocument();
Element root = doc.createElement("teacheer");
Element wang = doc.createElement("wang");
Element liu = doc.createElement("liu");
wang.appendChild(doc.createTextNode("This is teacher wang"));
liu.appendChild(doc.createTextNode("This is teacher liu"));
root.appendChild(wang);
doc.appendChild(root);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(new DOMSource(doc), new StreamResult(outFile));
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void readDom(String filename) {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new File(filename));
System.out.println(doc.getDocumentURI());
Element element = doc.getDocumentElement();
String rootTagName = element.getNodeName();
System.out.println("rootNODE:" + rootTagName);
NodeList nodeList = element.getChildNodes();
List
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private List
List
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Text) {
String value = node.getNodeValue();
if (value != null && !value.trim().equals("")) {
System.out.println("text:" + value);
}
}
if (node instanceof Element) {
if (node.getAttributes() != null && node.getAttributes().equals("")){
Element element = (Element)node;
System.out.println("tag:" + node.getNodeName() + " attr:" + element.getAttribute("id"));
} else {
System.out.println("tag:" + node.getNodeName());
}
}
tagInfo.add(node.getNodeName());
tagInfo.add(node.getNodeValue());
NodeList nodeChdList = node.getChildNodes();
tagInfo = getTagInfo(nodeChdList);
}
return tagInfo;
}
}
读取文件: