zoukankan      html  css  js  c++  java
  • Java中Dom解析xml文档

    xml文档

    <?xml version="1.0" encoding="UTF-8"?>
    <bookstore>
    	<book id="1">
    		<name>你好</name>
    		<author>李四</author>
    		<price>80</price>
    	</book>
    	<book id="2">
    		<name>你好2</name>
    		<author>李四2</author>
    		<price>81</price>
    	</book>
    </bookstore>
    

    java文件

    package cn.lonecloud.xml;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    
    public class DomXML {
    
    	public static void main(String[] args) throws Exception {
    		//先建立一个DocumentBuilderFactory对象
    		DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
    		//建立一个buildfactory对象
    		DocumentBuilder db=dbf.newDocumentBuilder();
    		//获取xml文件
    		Document document=db.parse("demo.xml");
    		//获取root树的Element
    		Element e1=document.getDocumentElement();
    		//获取子元素的子节点
    		if (e1!=null) {
    			NodeList list=e1.getChildNodes();
    			if (list!=null) {
    				//遍历书子节点
    				for (int i = 0; i < list.getLength(); i++) {
    					Node node=list.item(i);
    					if (node!=null) {
    						NodeList child=node.getChildNodes();
    						for (int j = 0; j < child.getLength(); j++) {
    							Node n=child.item(j);
    							//获取属性名称文本
    							if (n.getNodeType()==Node.ELEMENT_NODE) {
    								//获取节点名称
    								System.out.println(n.getNodeName());
    								//获取这个节点值
    								System.out.println(n.getFirstChild().getNodeValue());
    								//获取节点的的值下的所有文本
    								System.out.println(n.getTextContent());								
    							}
    						}
    					}
    				}
    			}
    		}
    	}
    
    }
    

      

  • 相关阅读:
    数据挖掘相关资料收集(持续更新)
    常见面试之机器学习算法思想简单梳理
    在c中保存状态
    lua 和 c
    lua 基础库
    lua 面向对象
    lua 高级
    lua 基础
    lua中的协程
    cocos2d中的可见性检测
  • 原文地址:https://www.cnblogs.com/lonecloud/p/5561686.html
Copyright © 2011-2022 走看看