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 + "    ");
    			}
    		}
    	}
    }
    


     

  • 相关阅读:
    python---读取/写入excel用例数据
    unitest框架--认识与基本使用
    python--模拟蜂窝网(https)登陆总结
    python--实践--模拟浏览器(http)登陆
    python--return小练习
    python--smtp邮件使用
    关于商城价格变动对订单影响的问题
    history.back新页面跳转
    PHP无限极分类
    htaccess分布式配置文件常用写法
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3249133.html
Copyright © 2011-2022 走看看