欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2020-10-12 09:31:33|栏目:JAVA代码|点击:

复制代码 代码如下:

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();
        }

       
    }
}

上一篇:浅谈Java 对于继承的初级理解

栏    目:JAVA代码

下一篇:SpringBoot启动报错Failed to determine a suitable driver class

本文标题:java解析xml之dom解析xml示例分享

本文地址:http://www.codeinn.net/misctech/10053.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有