【java与智能设备】CH11 Android中常见数据格式解析

布局文件 layout

Students.xml

<?xml version="1.0" encoding="utf-8"?>
<students>
    <student>
            <name sex="man">小明</name>
            <nickname>明明</nickname>    
    </student>    
    <student>
            <name sex="woman">小红</name>
            <nickname>红红</nickname>    
    </student>
</students>

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_dom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="DOM解析"/>
    <TextView
        android:id="@+id/tv_dom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="DOM解析结果:" />
    <Button
        android:id="@+id/btn_sax"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SAX解析"/>
    <TextView
        android:id="@+id/tv_sax"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="SAX解析结果:"/>

</LinearLayout>

MainActivity.java

package com.example.ch11xmlanalyzedemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

public class MainActivity extends AppCompatActivity {
    private Button btnDom;
    private TextView tvDom;
    private Button btnSax;
    private TextView tvSax;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViews();
        setListener();
    }

    private void findViews() {
        btnDom = findViewById(R.id.btn_dom);
        tvDom = findViewById(R.id.tv_dom);
        btnSax = findViewById(R.id.btn_sax);
        tvSax = findViewById(R.id.tv_sax);
    }

    private void setListener() {
        MyClickListener listener = new MyClickListener();
        btnDom.setOnClickListener(listener);
        btnSax.setOnClickListener(listener);
    }

    class MyClickListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            // 获取待解析文件的路径
            String file =
                    getFilesDir().getAbsolutePath() + "/students.xml";
            switch (view.getId()) {
                case R.id.btn_dom:
                    //使用DOM方式解析项目根目录下files文件夹中的xml文件
                    //采用DOM方式解析XML文件
                    analyzeXmlByDOM(file);
                    break;
                case R.id.btn_sax:
                    //使用SAX方式解析XML文件
                    analyzeXmlBySAX(file);
                    break;
            }
        }
    }

    /**
     * 采用SAX方式解析根目录下files中的XML文件
     * @param file
     */
    private void analyzeXmlBySAX(String file) {
        try {
            //1. 获取工厂类
            SAXParserFactory saxFactory =
                    SAXParserFactory.newInstance();
            //2. 获取解析器
            SAXParser parser = saxFactory.newSAXParser();
            //3. 获取阅读器
            XMLReader reader = parser.getXMLReader();
            //4. 创建自定义的事件类对象
            MySaxHander hander = new MySaxHander(tvSax);
            //5. 关联阅读器与事件处理对象
            reader.setContentHandler(hander);
            //6. 启动解析
            InputSource is =
                    new InputSource(new FileInputStream(file));
            reader.parse(is);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 采用DOM方式解析XML文件
     *
     * @param file
     */
    private void analyzeXmlByDOM(String file) {
        try {
            //1. 获取xml解析构建工厂对象
            DocumentBuilderFactory factory =
                    DocumentBuilderFactory.newInstance();
            //2. 创建XML解析的构建器
            DocumentBuilder builder = factory.newDocumentBuilder();
            //3. 将待解析的XML文件加载成Document
            Document document = builder.parse(new File(file));
            //4. 深度优先搜索方式解析DOM中的每个节点
            NodeList nodes = document.getElementsByTagName("student");
            //遍历获取到的节点集合
            //定义用于存储所有学生的集合对象
            List<Student> list = new ArrayList<>();
            for(int i = 0; i < nodes.getLength(); i++){
                //定义用于存储单个学生信息的Student
                Student student = new Student();
                Node node = nodes.item(i);//student节点
                NodeList childNodes = node.getChildNodes();
                //遍历子节点,获取所有子节点的值
                for(int j = 0; j < childNodes.getLength(); j++){
                    //获取当前的节点
                    Node childNode = childNodes.item(j);
                    //得到当前节点名称,并判断获取到的节点名称
                    String nodeName = childNode.getNodeName();
                    switch (nodeName){
                        case "name"://获取属性值、节点值
                            String name = childNode.getTextContent();
                            //获取属性
                            NamedNodeMap attrs = childNode.getAttributes();
                            //获取sex属性值
                            String sex = attrs.item(0).getTextContent();
                            student.setName(name);
                            student.setSex(sex);
                            break;
                        case "age":
                            //获取age节点的值
                            String content = childNode.getTextContent();
                            int age = Integer.parseInt(content);
                            student.setAge(age);
                            break;
                    }
                }
                list.add(student);
            }
            //把解析出来的内容显示在文本框
            tvDom.setText("DOM解析结果:" + list.toString());
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

MySaxHandler.java

package com.example.ch11xmlanalyzedemo;

import android.content.Context;
import android.widget.TextView;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.List;

public class MySaxHandler extends DefaultHandler {
    private List<Student> list;
    private String content;//用于存储节点值
    private Student student;
    private TextView tvSax;


    public MySaxHandler(TextView tvSax) {
        this.tvSax = tvSax;
    }

    public MySaxHandler() {
    }
    /**
     * 开始解析文档,通过做一些初始化逻辑操作
     * @throws SAXException
     */
    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        list = new ArrayList<>();
    }


    /**
     * 文件解析结束前调用,通常执行一些收尾工作
     * @throws SAXException
     */
    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        //显示解析的结果
        tvSax.setText("SAX解析结果:" + list.toString());
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        switch (qName){
            case "student":
                //初始化Student对象
                student = new Student();
                break;
            case "name":
                //获取到该标签的属性值
                String sex = attributes.getValue("sex");
                student.setSex(sex);
                break;
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        switch (qName){
            case "name":
                student.setName(content);
                content = "";
                break;
            case "age":
                int age = Integer.parseInt(content);
                student.setAge(age);
                content = "";
                break;
            case "student":
                list.add(student);
                content = "";
                break;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        content = new String(ch, start, length);
    }
}

Student.java

package com.example.ch11xmlanalyzedemo;

public class Student {
    private String name;
    private String sex;
    private int age;

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值