XMLPullParser - 跳过所有标签

时间:2017-01-11 22:21:32

标签: android xml android-xml xmlpullparser android-xmlpullparser

我需要使用XMLPullParser读取XML。但是当我尝试解析它时,我的eventType以0开始(即START_DOCUMENT)并立即跳到1(即END_DOCUMENT),从而跳过所有其他标签。

这是我的示例代码:

public void parseProperties (InputStream in)
{
    try
    {
        XmlPullParserFactory pullParserFactory = XmlPullParserFactory.newInstance();
        XmlPullParser pullParser = pullParserFactory.newPullParser();
        pullParser.setInput(in, null);

        int eventType = pullParser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT)
        {
            String name = pullParser.getName();
            switch (eventType)
            {
                case XmlPullParser.START_TAG:
                    break;
                case XmlPullParser.END_TAG:
                    break;
            }
            eventType = pullParser.next();
        }
    }
    catch (XmlPullParserException ex)
    {
    }
    catch (IOException ex)
    {
    }
    finally
    {

    }
}

有人可以告诉我为什么我无法打开任何开关案件吗?

1 个答案:

答案 0 :(得分:1)

这对我来说总是有用的:

public class ParseXML {

    private String xmlData;

    public ParseXML (String xmlData) {

        this.xmlData = xmlData;
    }

    public boolean process () {

        boolean status = true;
        boolean inEntry = false;
        String textValue = "";

        try {

            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser xpp = factory.newPullParser();
            xpp.setInput(new StringReader(this.xmlData));

            int eventType = xpp.getEventType();

            while (eventType != XmlPullParser.END_DOCUMENT) {

                String tagName = xpp.getName();

                switch (eventType) {

                    case XmlPullParser.START_TAG:
                        if (tagName.equalsIgnoreCase("MyTagStart")) {
                            inEntry = true;
                        }
                        break;

                    case XmlPullParser.TEXT:
                        textValue = xpp.getText();
                        break;

                    case XmlPullParser.END_TAG:
                        if (inEntry) {
                            if (tagName.equalsIgnoreCase("MyTagEnd")) {
                                inEntry = false;
                            }
                            else if (tagName.equalsIgnoreCase("SomeTag")) {
                                someInfo.setInfo(textValue);
                            }
                        }
                        break;

                    default:
                        //
                }
                eventType = xpp.next();
            }

        } catch (Exception e) {

            status = false;
            e.printStackTrace();
        }

        return true;
    }
}

您只需创建一个传递XML数据的实例:

ParseXML parseXML = new ParseXML(contentXML);
parseXML.process();