您的位置:首页 > 其它

递归打印XML文档树-使用w3cDOM模型解析

2016-03-08 22:38 543 查看
如题,使用w3c xml parse api来把内存中的Document文档树对象打印到控制台

package xml;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

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;

public class TestXml {

public static void main(String[] args) throws Exception {
Class<TestXml> testXmlClazz = TestXml.class;
InputStream is = testXmlClazz.getResourceAsStream("???.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
Element root = doc.getDocumentElement();
parseElement(root);
}

private static void parseElement(Element ele) {
System.out.print("<" + ele.getTagName());
// 打印标签的属性
NamedNodeMap attris = ele.getAttributes();
for(int i = 0; i < attris.getLength(); i++) {
Attr attr = (Attr) attris.item(i);
System.out.print(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
}
System.out.println(">");
// 获取子标签
NodeList childNodes = ele.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node childNode = childNodes.item(i);
if (childNode.getNodeType() == Node.ELEMENT_NODE) {
// 递归处理子标签
parseElement((Element) childNode);
} else if (childNode.getNodeType() != Node.COMMENT_NODE) {
System.out.println(childNode.getTextContent().trim());
}
}
System.out.println("</" + ele.getTagName() + ">");
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  递归 xml w3c 数据 对象