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


     

  • 相关阅读:
    uni-appios端app白屏问题
    vue中倒计时假清除
    vue路由守卫
    JS函数命名规范
    VUE生成二维码
    移动端H5之css配置rem
    关于在vue中使用ui库样式无法修改的问题
    v28 error: resource android:attr/dialogCornerRadius not found.
    cocos2d: fullPathForFilename: No file found at script/jsb_prepare.js. Possible missing file
    android studio clean show: CreateProcess error=2, 系统找不到指定的文件。
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3249133.html
Copyright © 2020-2023  润新知