Android-XML

XML文件:

<?xml version="1.0" encoding="utf-8"?>
<books>
    <book id="1">
        <name>C# 入门经典</name>
        <price>10</price>
        <des>Good</des>
    </book>
    <book id="2">
        <name>C# 高级编程</name>
        <price>20</price>
        <des>Good</des>
    </book>
    <book id="3">
        <name>Android 第一行代码</name>
        <price>30</price>
        <des>Good</des>
    </book>
</books>

1.PULL解析器

(1)解析XML

    public static List<Ben_Book> decodeXMLByPULL(InputStream inputStream) {

        List<Ben_Book> list = null;
        Ben_Book book = null;

        //1.创建XmlPUlParser实例
        XmlPullParser parser = Xml.newPullParser();
        try {
            //2.设置数据流,指明编码方式
            parser.setInput(inputStream, "utf-8");
            //3.获取事件类型
            int eventType = parser.getEventType();
            //4.判断事件类型,只要不是文档结束,就继续解析
            while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {

                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT: //文档开始位置
                        list = new ArrayList<>();
                        break;
                    case XmlPullParser.START_TAG: //标签开始
                        String name = parser.getName();
                        if (name.equals("book")) {
                            book = new Ben_Book();
                            String id= parser.getAttributeValue(0); //获取属性值
                            book.setId(id);
                        } else if (name.equals("name")) {
                            book.setName(parser.nextText().toString()); //获取节点内容
                        } else if (name.equals("price")) {
                            book.setPrice(parser.nextText().toString());
                        } else if (name.equals("des")) {
                            book.setDes(parser.nextText().toString());
                        }
                        break;
                    case XmlPullParser.END_TAG: //标签结束
                        list.add(book); //book 添加到集合当中
                        book = null;
                        break;
                    case XmlPullParser.END_DOCUMENT: //文档结束
                        break;
                }

                eventType = parser.next(); //解析下一个事件
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

(2)生成XML文件

public String writeXML(List<Book> list) throws XmlPullParserException, IOException {

    XmlSerializer serializer = XmlPullParserFactory.newInstance().newSerializer();
    StringWriter sw = new StringWriter();
    serializer.setOutput(sw);
    serializer.startDocument("utf-8", true);
    serializer.startTag("", "books"); //根节点

    for (Book book : list) {

        serializer.startTag("", "book");  //*******//
        serializer.attribute("", "id", book.getId());

        serializer.startTag("", "name");
        serializer.text(book.getName());
        serializer.endTag("", "name");

        serializer.startTag("", "price");
        serializer.text(book.getPrice());
        serializer.endTag("", "price");

        serializer.startTag("", "des");
        serializer.text(book.getDescription());
        serializer.endTag("", "des");

        serializer.endTag("","book"); //********//
    }
    serializer.endTag("", "books");
    serializer.endDocument();
    String xml = sw.toString();
    System.out.println(xml);
    return xml;
}

2.DOM解析器

(1)解析

   public static List<Ben_Book> decodeXMLByDOM(InputStream inputStream) {

        List<Ben_Book> list = new ArrayList<>();
        Ben_Book book;
        try {
            //1.获得DOM解析器的工厂示例:
            //DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            //2.从Dom工厂中获得dom解析器
            //DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
            //3.xml数据流读入Dom解析器
            //Document doc = dbBuilder.parse(inputStream);
            //或者可以一步到位
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
            //4.得到文档中名称为book的元素的结点列表
            NodeList nList = doc.getElementsByTagName("book");
            //5.遍历该集合,显示集合中的元素以及子元素的名字
            for (int i = 0; i < nList.getLength(); i++) {
                //先从book元素开始解析
                Element bookElement = (Element) nList.item(i);
                book = new Ben_Book();
                book.setId(bookElement.getAttribute("id")); //获取属性值

                //获取book下的name,price,des
                NodeList childNoList = bookElement.getChildNodes();
                for (int j = 0; j < childNoList.getLength(); j++) {
                    Node childNode = childNoList.item(j);
                    //判断子note类型是否为元素Note
                    if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element childElement = (Element) childNode;
                        if ("name".equals(childElement.getNodeName()))
                            book.setName(childElement.getFirstChild().getNodeValue());
                        else if ("price".equals(childElement.getNodeName()))
                            book.setPrice(childElement.getFirstChild().getNodeValue());
                        else if ("des".equals(childElement.getNodeName()))
                            book.setDes((childElement.getFirstChild().getNodeValue()));
                    }
                }
                list.add(book);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
Last modification:January 14th, 2020 at 08:02 pm