如题,使用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() + ">");
}
}