0

我需要使用 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
    {

    }
}

有人可以告诉我为什么我无法点击任何开关盒吗?

4

1 回答 1

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();
于 2017-01-11T22:30:21.810 回答