网络编程--xml数据解析

  • xml数据解析共有三种解析方式SAX,DOM和PULL。
  • 其中的SAX和DOM解析在IO处理这篇博客中进行了详细的解释,这里就不再重复了。
  • 我们重点讲解一下PULL解析

PULL解析xml

  • 其实PULL解析xml和DOM解析非常的相似
  • 要解析的数据如下
<?xml version="1.0" encoding="utf-8"?>
<apps>
    <app>
        <id>1</id>
        <name>zhangsan</name>
        <age>18</age>
    </app>
    <app>
        <id>2</id>
        <name>lisi</name>
        <age>8</age>
    </app>
    <app>
        <id>2</id>
        <name>wangwu</name>
        <age>25</age>
    </app>
</apps>
  • 我们先来看代码
public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button button_pull,button_sax,button_dom;
    private String data;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();

        data="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                "<apps>\n" +
                "\t<app>\n" +
                "\t\t<id>1</id>\n" +
                "\t\t<name>zhangsan</name>\n" +
                "\t\t<age>18</age>\n" +
                "\t</app>\n" +
                "\t<app>\n" +
                "\t\t<id>2</id>\n" +
                "\t\t<name>lisi</name>\n" +
                "\t\t<age>8</age>\n" +
                "\t</app>\n" +
                "\t<app>\n" +
                "\t\t<id>2</id>\n" +
                "\t\t<name>wangwu</name>\n" +
                "\t\t<age>25</age>\n" +
                "\t</app>\n" +
                "</apps>";
    }

    private void init() {
        button_pull= (Button) findViewById(R.id.button_pull);
        button_sax= (Button) findViewById(R.id.button_sax);
        button_dom= (Button) findViewById(R.id.button_dom);
        button_pull.setOnClickListener(this);
        button_sax.setOnClickListener(this);
        button_dom.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button_pull:
                pullXML();
                break;
            case R.id.button_sax:
                saxXML();
                break;
            case R.id.button_dom:
                domXML();
                break;
        }
    }

    //PULL解析XML的代码
    private void pullXML() {
        try {
            //首先实例化一个PULL解析器工厂
            XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
            //通过解析器工厂获取一个XmlPullParser对象
            XmlPullParser parser=factory.newPullParser();
            //通过XmlPullParser将要解析的数据传入
            parser.setInput(new StringReader(data));
            //获取当前的节点的类型
            int eventType=parser.getEventType();
            String id="";
            String name="";
            String age="";
            //判断节点类型是否是文档结尾,是的话停止解析,未到文档尾,继续解析
            while (eventType!=XmlPullParser.END_DOCUMENT){
                //获取当前的节点名称
                String nodeName=parser.getName();
                //判断当前的节点类型
                switch (eventType){
                    //如果是标签TAG开始类型,一个TAG就是一个<app></app>中的所有内容
                    case XmlPullParser.START_TAG:
                        if ("id".equals(nodeName)){
                            id=parser.nextText();
                        }else if ("name".equals(nodeName)){
                            name=parser.nextText();
                        }else if ("age".equals(nodeName)){
                            age=parser.nextText();
                        }
                        break;
                    ////如果是标签TAG结束类型,就将所有输出即可
                    case XmlPullParser.END_TAG:
                        if ("app".equals(nodeName)){
                            Log.d("***",id+name+age);
                        }
                        break;
                }
                //解析完一个TAG就将节点往下移一个节点。
                eventType=parser.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //SAX解析XML的代码
    private void saxXML() {
        SAXParserFactory factory=SAXParserFactory.newInstance();
        try {
            SAXParser parser=factory.newSAXParser();
            parser.parse(new InputSource(new StringReader(data)),new MyHandler());

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //DOM解析XML的代码
    private void domXML() {
        DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder=builderFactory.newDocumentBuilder();
            Document document=builder.parse(new InputSource(new StringReader(data)));
            NodeList list=document.getElementsByTagName("app");
            for (int i=0;i<list.getLength();i++){
                Node node=list.item(i);
                Node child=node.getFirstChild();

                String id="";
                String name="";
                String age="";

                while (child!=null){
                    if (child.getNodeType()==Node.ELEMENT_NODE){
                        String nodeName=child.getNodeName();
                        if ("id".equals(nodeName)){
                            id=child.getFirstChild().getNodeValue();
                        }else if ("name".equals(nodeName)){
                            name=child.getFirstChild().getNodeValue();
                        }else if ("age".equals(nodeName)){
                            age=child.getFirstChild().getNodeValue();
                        }
                    }
                    child=child.getNextSibling();
                }
                Log.d("***",id+name+age+"****");

            }

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 这里是SAX解析XML的自定义的DefaultHanlder对象
public class MyHandler extends DefaultHandler {
    private String id="";
    private String name="";
    private String age="";
    private String nodeName;

    @Override
    public void startDocument() throws SAXException {
        Log.d("***","开始解析文档");
    }

    @Override
    public void endDocument() throws SAXException {
        Log.d("***","开始解析文档");
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        nodeName=qName;
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        if ("app".equals(qName)){
            Log.d("***",id+name+age);
        }
        nodeName="";
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        String data=new String(ch,start,length);
        if ("id".equals(nodeName)){
            id=data;
        }else if ("name".equals(nodeName)){
            name=data;
        }else if ("age".equals(nodeName)){
            age=data;
        }
    }
}
  • 其中有关SAX和DOM解析XML的讲解在IO处理这篇博客中,需要的请自行查看

你可能感兴趣的:(xml,dom,sax,网络编程,pull)