1. 程式人生 > >Java 手動解析xml資料

Java 手動解析xml資料

公司裡跟伺服器基本都是用json資料進行資料互動,用xml的還真是少。不過抱著負責任的態度(- -!),咳咳。。。還是上tomcat吧。用tomcat模擬伺服器,在伺服器端的MyHttp工程目錄下存在person.xml。本地訪問伺服器得到xml資料後分別進行pull和sax解析。

伺服器端的person.xml

<?xml version = "1.0" encoding = "UTF-8"?>
<persons>
    <person id = "23">
        <name>張老師</name>
        <age
>
21</age> </person> <person id = "20"> <name>李老師</name> <age>25</age> </person> </persons>

pull解析PullParser.java

public class PullParser {

    public List<Person>  parser(String path) throws XmlPullParserException, IOException {
        List<Person> list = null
; Person person = null; XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); InputStream in = HttpUtil.getInputStream(path); parser.setInput(in, "utf-8"); int event = parser.getEventType(); while
(event!=XmlPullParser.END_DOCUMENT) { switch(event) { case XmlPullParser.START_DOCUMENT: list = new ArrayList<Person>();break; case XmlPullParser.START_TAG: String tagName = parser.getName(); if("person".equals(tagName)) { person = new Person(); int count = parser.getAttributeCount(); for(int i=0;i<count;i++) { String atrrName = parser.getAttributeName(i); String attrValue = parser.getAttributeValue(i); if("id".equals(atrrName)) person.setId(attrValue); } } else if("name".equals(tagName)) { person.setName(parser.nextText()); } else if("age".equals(tagName)) { person.setAge(Integer.parseInt(parser.nextText())); } break; case XmlPullParser.END_TAG: if("person".equals(parser.getName())) list.add(person); break; } event = parser.next(); } return list; } }

sax解析MyHandler.java

public class MyHandler extends DefaultHandler {

    private List<Person> list;
    private Person person;
    private String tagName;

    @Override
    public void startDocument() throws SAXException {
        list = new ArrayList<Person>();
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        tagName = qName;
        if("person".equals(qName)) {
            person = new Person();
            for(int i=0;i<attributes.getLength();i++) {
                String attrName = attributes.getQName(i);
                String attrValue = attributes.getValue(i);
                if("id".equals(attrName))
                    person.setId(attrValue);
            }
        }
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        String data = new String(ch,start,length);
        if("name".equals(tagName))
            person.setName(data);
        else if("age".equals(tagName))
            person.setAge(Integer.parseInt(data));
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        tagName = null;
        if("person".equals(qName))
            list.add(person);

    }

    @Override
    public void endDocument() throws SAXException {

    }

    public List<Person> getList() {
        return list;
    } 
}

本地用來存放資料的實體類Person.java

public class Person {

    private String id;
    private String name;
    private int age;

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

    public Person(String id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

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

}

訪問模擬伺服器的工具類HttpUtil.java

public class HttpUtil {

    public static InputStream getInputStream(String path) throws IOException {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        conn.setDoInput(true);

        conn.connect();
        InputStream in =null;
        if(conn.getResponseCode()==200) {
            in = conn.getInputStream();
        }
        return in;

    }

}

程式入口

最後呼叫

/**pull*/
public static void main(String[] args) throws XmlPullParserException, IOException {

    String path = "http://localhost:8080/MyHttp/person.xml";

    PullParser parser = new PullParser();

    List<Person> list =parser.parser(path);

    for(Person person:list) {
        System.out.println(person);
    }
}
/**sax*/
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {

    String path = "http://localhost:8080/MyHttp/person.xml";
    SAXParserFactory factory = SAXParserFactory.newInstance();

    SAXParser parser =factory.newSAXParser();

    InputStream in = HttpUtil.getInputStream(path);
    MyHandler handler = new MyHandler();

    parser.parse(in, handler);

    List<Person> list = handler.getList();
    for(Person person:list) {
        System.out.println(person);
    }
}