服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - JAVA教程 - java解析xml之dom解析xml示例分享

java解析xml之dom解析xml示例分享

2019-10-27 12:30java技术网 JAVA教程

DOM将整个XML文件加载到内存中,并构建出节点树;应用程序可以通过遍历节点树的方式来解析XML文件中的各个节点、属性等信息; 这种方式便于对XML节点的添加修改等,而且解析也很方便,然后它比较耗费内存,解析速度也不快,

代码如下:


package com.test;

 

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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) {
        try {
            File file = new File("e:/People.xml");  
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();   
            DocumentBuilder builder = factory.newDocumentBuilder();   
            Document document = builder.parse(file);   
            Element element = document.getDocumentElement();

            List<People> peopleList = new ArrayList<People>();
            NodeList peopleNodes = element.getElementsByTagName("People"); 
            for(int i=0;i<peopleNodes.getLength();i++){   
                People people = new People();
                Element peopleElement = (Element) peopleNodes.item(i);
                people.setId(peopleElement.getAttribute("id"));
                NodeList childPeopleNodes = peopleElement.getChildNodes();
                for(int j=0;j<childPeopleNodes.getLength();j++){
                    //DOM解析时候注意子节点前面的空格也会被解析
                    if(childPeopleNodes.item(j) instanceof Element){
                        Element childPeopleElement = (Element) childPeopleNodes.item(j);
                        if(childPeopleElement.getNodeType()==Node.ELEMENT_NODE){  
                            if(childPeopleElement.getNodeName().equals("Name")){
                                people.setEnglishName(childPeopleElement.getAttribute("en"));
                                people.setName(childPeopleElement.getTextContent());
                            }
                            else if(childPeopleElement.getNodeName().equals("Age")){
                                people.setAge(childPeopleElement.getTextContent());    
                            }
                        }
                    }
                }
                peopleList.add(people);
            }

            for(People people : peopleList){
                System.out.println(people.getId()+"\t"+people.getName()+"\t"+people.getEnglishName()+"\t"+people.getAge());
            }

        } catch (Exception e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } 

        
    }
}

 

延伸 · 阅读

精彩推荐