Android:任何人都可以帮我解析XML吗?

时间:2016-11-13 17:41:27

标签: android json xml android-studio

我正在为Android创建一个图库应用程序,我最近开始为Android开发 我正在尝试解析XML,但互联网上的所有示例都不适用于我

XML

任何人都可以为我解析并发送代码吗?

1 个答案:

答案 0 :(得分:1)

试试这个,

public List<Foto> getFotos() {
    ArrayList<Foto> array = new ArrayList<>();
    Foto foto = new Foto();

    try {
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser parser = factory.newPullParser();

        InputStream inputStream = getAssets().open("fotos.xml");
        parser.setInput(inputStream, null);

        int eventType = parser.getEventType();
        String text = "";

        while (eventType != XmlPullParser.END_DOCUMENT) {
            eventType = parser.next();
            String tagName = parser.getName();

            switch (eventType) {
                case XmlPullParser.START_TAG:
                    if (tagName.equals("foto")) {
                        foto = new Foto();
                    }
                    break;
                case XmlPullParser.END_TAG:
                    if (tagName.equals("foto")) {
                        array.add(foto);
                    } else if (tagName.equals("title")) {
                        foto.setTitle(text);
                    } else if (tagName.equals("nome")) {
                        foto.setNome(text);
                    }
                    break;
                case XmlPullParser.TEXT:
                    text = parser.getText();
                    break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return array;
}

Foto.java

public class Foto {
    String title;
    String nome;

    public Foto() {
    }

    public Foto(String title, String nome) {
        this.title = title;
        this.nome = nome;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }
}