zoukankan      html  css  js  c++  java
  • JAVA读取XML,JAVA读取XML文档,JAVA解析XML文档,JAVA与XML,XML文档解析(Document Object Model, DOM)

    使用Document Object Model, DOM解析XML文档

    也可参考我的新浪博客:http://blog.sina.com.cn/s/blog_43ac5543010190w3.html

     测试代码如下

    package main;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    
    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;
    
    public class Test {
    
    	public static void main(String[] args) throws Exception {
    
    		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    		DocumentBuilder builder = factory.newDocumentBuilder();
    		factory.setIgnoringElementContentWhitespace(true);
    		factory.setIgnoringComments(true);
    		factory.setValidating(true);
    
    		Document xmlDoc = builder.parse("C:/test.xml");
    		Element root = xmlDoc.getDocumentElement();
    
    		listNodes(root, "");
    	}
    
    	public static void listNodes(Node node, String space) {
    		Element element = null;
    		// if (node instanceof Element) {
    		if (node.getNodeType() == Node.ELEMENT_NODE) {
    			element = (Element) node;
    			Text textNode = (Text) element.getFirstChild();
    			
    			String tagName = element.getTagName();
    			String tagValue = textNode.getData().trim();
    			System.out.print(space + tagName);
    			if (!"".equals(tagValue)) {
    				System.out.print("=" + tagValue);
    			}
    			
    			NamedNodeMap attributes = element.getAttributes();
    			for (int i = 0; i < attributes.getLength(); i++) {
    				Node attribute = attributes.item(i);
    				String name = attribute.getNodeName();
    				String value = attribute.getNodeValue();
    				System.out.print("    " + name + ":" + value);
    			}
    			System.out.println();
    		}
    
    		NodeList list = node.getChildNodes();
    		int childNodesLength = list.getLength();
    		if (childNodesLength > 0) {
    			for (int i = 0; i < childNodesLength; i++) {
    				listNodes(list.item(i), space + "    ");
    			}
    		}
    	}
    }
    


     

  • 相关阅读:
    软件工程第一周开课博客
    求数组的子数组之和的最大值
    学习进度_第二周
    当堂测试感受
    寒假生活体验
    家庭记账本七
    《人月神话》阅读笔记3
    家庭记账本六
    《人月神话》阅读笔记2
    寒假福利2
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3249133.html
Copyright © 2011-2022 走看看