美文网首页
xml格式解析

xml格式解析

作者: Crane_FeiE | 来源:发表于2018-09-22 07:25 被阅读0次

    使用Pull解析方式,对每个节点一个个进行解析。

    public class XmlParseTestActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_xml_parse_test);
        }
    
        private void sendRequestWithOkHttp() {
            new Thread(new Runnable() {
                @Override
                public void run() {
    
                    try {
                        OkHttpClient client = new OkHttpClient();
                        Request request = new Request.Builder()
                                .url("192.168.1.1/ok.xml")
                                .build();
                        Response response = client.newCall(request).execute();
                        String responseString = response.body().string();
                        parseXml(responseString);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    
                }
            }).start();
        }
    
        private void parseXml(String responseString) {
            try {
                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                XmlPullParser parser = factory.newPullParser();
                parser.setInput(new StringReader(responseString));
                int eventType = parser.getEventType();
                String id = "";
                String name = "";
                String version = "";
                String nodeName = parser.getName();
                while (eventType != XmlPullParser.END_DOCUMENT) {
                    switch (eventType) {
                        case XmlPullParser.START_TAG:
                            if ("id".equals(nodeName)) {
                                id = parser.nextText();
                            } else if ("name".equals(nodeName)) {
                                name = parser.nextText();
                            } else if ("version".equals(nodeName)) {
                                version = parser.nextText();
                            }
                            break;
                        //完成一个节点的解析
                        case XmlPullParser.END_TAG:
                            if ("app".equals(nodeName)) {
                                Log.i("lyh", "id and name and version:" + id + ", " + name + ", " + version);
                            }
                            break;
                        default:
                            break;
                    }
                    eventType = parser.next();
                }
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    遗留问题:
    XmlPullParser适用于哪些情况??


    使用SAX解析方式 (Simple Api for Xml)

    • 用法较PullParser稍微复杂一点
    • 语意清晰

    1. 写一个自定义的Handler类继承DefaultHandler,实现如下几个方法:

    public class MySAXHandler extends DefaultHandler {
    
        private String eleName;
        private StringBuilder id;
        private StringBuilder name;
        private StringBuilder version;
    
        /**
         * called when start parsing a xml document
         * @throws SAXException
         */
        @Override
        public void startDocument() throws SAXException {
            id = new StringBuilder();
            name = new StringBuilder();
            version = new StringBuilder();
        }
    
        /**
         * Receive notification of the start of an element.
         *
         * <p>By default, do nothing.  Application writers may override this
         * method in a subclass to take specific actions at the start of
         * each element (such as allocating a new tree node or writing
         * output to a file).</p>
         *
         * @param uri The Namespace URI, or the empty string if the
         *        element has no Namespace URI or if Namespace
         *        processing is not being performed.
         * @param localName The local name (without prefix), or the
         *        empty string if Namespace processing is not being
         *        performed.
         * @param qName The qualified name (with prefix), or the
         *        empty string if qualified names are not available.
         * @param attributes The attributes attached to the element.  If
         *        there are no attributes, it shall be an empty
         *        Attributes object.
         * @exception org.xml.sax.SAXException Any SAX exception, possibly
         *            wrapping another exception.
         * @see org.xml.sax.ContentHandler#startElement
         */
        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            eleName = localName;
        }
    
        /**
         * Receive notification of character data inside an element.
         *
         * <p>By default, do nothing.  Application writers may override this
         * method to take specific actions for each chunk of character data
         * (such as adding the data to a node or buffer, or printing it to
         * a file).</p>
         *
         * @param ch The characters.
         * @param start The start position in the character array.
         * @param length The number of characters to use from the
         *               character array.
         * @exception org.xml.sax.SAXException Any SAX exception, possibly
         *            wrapping another exception.
         * @see org.xml.sax.ContentHandler#characters
         */
        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            super.characters(ch, start, length);
            if("id".equals(eleName)){
                id.append(ch, start, length);
            } else if("name".equals(eleName)){
                name.append(ch, start, length);
            } else if ("version".equals(eleName)){
                version.append(ch, start, length);
            }
        }
    
        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            super.endElement(uri, localName, qName);
            //finished parsing one element, you should clear your String Builders here
            id.setLength(0);
            name.setLength(0);
            version.setLength(0);
        }
    
        @Override
        public void endDocument() throws SAXException {
            super.endDocument();
            //for this occasion, we don't have to do anything
        }
    }
    

    2.将上一节parseXml方法修改为parseXmlWithSax方法

        private void parseXmlWithSAX(String responseString) {
            try {
                SAXParserFactory factory = SAXParserFactory.newInstance();
                XMLReader reader = factory.newSAXParser().getXMLReader();
                MySAXHandler saxHandler = new MySAXHandler();
                reader.setContentHandler(saxHandler);
                reader.parse(new InputSource(new StringReader(responseString)));
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    

    相关文章

      网友评论

          本文标题:xml格式解析

          本文链接:https://www.haomeiwen.com/subject/benonftx.html