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

来源:互联网 发布:js转html 编辑:程序博客网 时间:2024/06/03 06:06

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


0 0
原创粉丝点击