android 中对xml 进行解析

来源:互联网 发布:windows用什么系统写的 编辑:程序博客网 时间:2024/06/03 23:01
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->person.xml

<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person id="1">
        <name>Jerry</name>
        <age>23</age>
    </person>
    
    <person id="3">
        <name>Lily</name>
        <age>17</age>
    </person>

</persons>

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->针对person创建javabean,(因为我们下面要以对象的形式获取此xml文件内容)

package cn.partner4java.xml.bean;

public class Person {
    private int id;
    private String name;
    private short age;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public short getAge() {
        return age;
    }
    public void setAge(short age) {
        this.age = age;
    }

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->/**
 * 使用Dom解析xml文件
 *
 */
public class DomXMLReader {

public static List<Person> readXML(InputStream inStream) {
    List<Person> persons = new ArrayList<Person>();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document dom = builder.parse(inStream);
        Element root = dom.getDocumentElement();
        NodeList items = root.getElementsByTagName("person");//查找所有person节点
        for (int i = 0; i < items.getLength(); i++) {
            Person person = new Person();
            //得到第一个person节点
            Element personNode = (Element) items.item(i);
            //获取person节点的id属性值
            person.setId(new Integer(personNode.getAttribute("id")));
            //获取person节点下的所有子节点(标签之间的空白节点和name/age元素)
            NodeList childsNodes = personNode.getChildNodes();
            for (int j = 0; j < childsNodes.getLength(); j++) {
            Node node = (Node) childsNodes.item(j);             
               //判断是否为元素类型
            if(node.getNodeType() == Node.ELEMENT_NODE){                       
                 Element childNode = (Element) node;
                  //判断是否name元素
                if ("name".equals(childNode.getNodeName())) {
                 //获取name元素下Text节点,然后从Text节点获取数据                       
                 person.setName(childNode.getFirstChild().getNodeValue());
                } else if (“age”.equals(childNode.getNodeName())) {
            person.setAge(new Short(childNode.getFirstChild().getNodeValue()));
                }
            }
                }
            persons.add(person);
        }
        inStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return persons;
}



原创粉丝点击