dom方法读取xml(不常用)

时间:2021-11-30 00:09:51

Book.java

package com.xml.demo;

public class Book {
    private int id;
    private String name;
    private Float money;

    public int getId() {
        return id;
    }

    @Override
    public String toString() {
        return "Book [id=" + id + ", name=" + name + ", money=" + money + "]";
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    public Book() {
        // TODO Auto-generated constructor stub
    }

}

DemoServer.java

package com.xml.demo;

import java.io.InputStream;
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 DemoServer {

    public DemoServer() {
        // TODO Auto-generated constructor stub
    }

    public List<Book> getBooks(InputStream inputstream) throws Exception
    {
        List<Book> list=new ArrayList<Book>();
        //创建一个document工厂
        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
        DocumentBuilder builder=factory.newDocumentBuilder();
        Document document=builder.parse(inputstream);
        Element element=document.getDocumentElement();//获得稳定的元素节点
        NodeList bookNodes=element.getElementsByTagName("book");
        for(int i=0;i<bookNodes.getLength();i++)
        {
            Element bookElement=(Element) bookNodes.item(i);
            Book book=new Book();
            book.setId(Integer.parseInt(bookElement.getAttribute("id")));
            NodeList childNodes=bookElement.getChildNodes();
            for(int j=0;j<childNodes.getLength();j++)
            {
                if(childNodes.item(j).getNodeType()==Node.ELEMENT_NODE)
                {
                    if("name".equals(childNodes.item(j).getNodeName()))
                    {
                        book.setName(childNodes.item(j).getFirstChild().getNodeValue());
                    }else if("price".equals(childNodes.item(j).getNodeName()))
                    {
                        book.setMoney(Float.parseFloat(childNodes.item(j).getFirstChild().getNodeValue()));
                    }
                }
            }
            list.add(book);
        }
        return list;

    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        String path="http://weikew.gotoip55.com/person.xml";
        InputStream inputstream=HttpUtils.getXML(path);
        DemoServer server=new DemoServer();
        try {
            List<Book> list=server.getBooks(inputstream);
            for(Book book:list)
            {
                System.out.println(book.toString());
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

    }

}

HttpUtils.java

package com.xml.demo;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {

    public HttpUtils() {
        // TODO Auto-generated constructor stub
    }
    public static InputStream getXML(String path)
    {
        InputStream inputStream=null;
        try {
            URL url=new URL(path);
            if(url!=null)
            {
                HttpURLConnection connection=(HttpURLConnection)url.openConnection();
                connection.setConnectTimeout(3000);
                connection.setDoInput(true);
                connection.setRequestMethod("GET");
                int code=connection.getResponseCode();
                if(code==200)
                {
                    inputStream=connection.getInputStream();
                }

            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return inputStream;

    }

}

person.xml

<?xml version="1.0" encoding="utf-8"?>
<books>
<book id="20"><name>张老进</name><price>22.2</price></book>
<book id="33"><name>李法在</name><price>44.5</price></book></books>