在Android中使用XMLPullParser解析本地XML文件

时间:2013-09-25 10:23:19

标签: java android xml xmlpullparser

这就是我想要做的。我写了一个应该处理我的XML文件的类。

    package de.lies;

    import java.io.IOException;

    import org.xmlpull.v1.XmlPullParser;
    import org.xmlpull.v1.XmlPullParserException;

    public class Entry {
    private static final String ns = null;

    public final String rank;
    public final String source; 
    public final String date;
    public final String headline;
    public final String description;
    public final String articleURL;
    public final String sourceURL;
    public final String imageURL;

    private Entry(String rank, String source, String date, String headline, String description, String articleURL, String sourceURL, String imageURL){
        this.rank           = rank;
        this.source         = source;
        this.date           = date;
        this.headline       = headline;
        this.description    = description;
        this.articleURL     = articleURL;
        this.sourceURL      = sourceURL;
        this.imageURL       = imageURL;
    }

    private Entry readEntry (XmlPullParser parser) throws XmlPullParserException, IOException{
        parser.require(XmlPullParser.START_TAG, ns, "entry");
        String rank         = null;
        String source       = null;
        String date         = null;
        String headline     = null;
        String description  = null;
        String articleURL   = null;
        String sourceURL    = null;
        String imageURL     = null;

        while(parser.next() != XmlPullParser.END_TAG) {
            if(parser.getEventType() != XmlPullParser.START_TAG){
                continue;
            }
            String name     = parser.getName();

            if(name.equals("rank")){
                rank        = readRank(parser);
            } else if(name.equals("source")){
                source      = readSource(parser);
            } else if(name.equals("date")){
                date        = readDate(parser);
            } else if(name.equals("headline")){
                headline    = readHeadline(parser);
            } else if(name.equals("description")){
                description = readDescription(parser);
            } else if(name.equals("articleURL")){
                articleURL  = readArticleURL(parser);
            } else if(name.equals("sourceURL")){
                sourceURL   = readSourceURL(parser);
            } else if(name.equals("imageURL")){
                imageURL    = readImageURL(parser);
            } else {
                skip(parser);
            }
        }
        return new Entry(rank, source, date, headline, description, articleURL, sourceURL, imageURL);
    }

    private String readRank(XmlPullParser parser) throws IOException, XmlPullParserException{
        parser.require(XmlPullParser.START_TAG, ns, "rank");
        String rank         = readText(parser);

        parser.require(XmlPullParser.END_TAG, ns, "rank");
        return rank;
    }

    private String readSource(XmlPullParser parser) throws IOException, XmlPullParserException{
        parser.require(XmlPullParser.START_TAG, ns, "source");
        String source       = readText(parser);

        parser.require(XmlPullParser.END_TAG, ns, "source");
        return source;
    }

    private String readDate(XmlPullParser parser) throws IOException, XmlPullParserException{
        parser.require(XmlPullParser.START_TAG, ns, "rank");
        String date         = readText(parser);

        parser.require(XmlPullParser.END_TAG, ns, "rank");
        return date;
    }

    private String readHeadline(XmlPullParser parser) throws IOException, XmlPullParserException{
        parser.require(XmlPullParser.START_TAG, ns, "rank");
        String headline     = readText(parser);

        parser.require(XmlPullParser.END_TAG, ns, "rank");
        return headline;
    }

    private String readDescription(XmlPullParser parser) throws IOException, XmlPullParserException{
        parser.require(XmlPullParser.START_TAG, ns, "rank");
        String description      = readText(parser);

        parser.require(XmlPullParser.END_TAG, ns, "rank");
        return description;
    }

    private String readArticleURL(XmlPullParser parser) throws IOException, XmlPullParserException{
        parser.require(XmlPullParser.START_TAG, ns, "rank");
        String articleURL       = readText(parser);

        parser.require(XmlPullParser.END_TAG, ns, "rank");
        return articleURL;
    }

    private String readSourceURL(XmlPullParser parser) throws IOException, XmlPullParserException{
        parser.require(XmlPullParser.START_TAG, ns, "rank");
        String sourceURL        = readText(parser);

        parser.require(XmlPullParser.END_TAG, ns, "rank");
        return sourceURL;
    }

    private String readImageURL(XmlPullParser parser) throws IOException, XmlPullParserException{
        parser.require(XmlPullParser.START_TAG, ns, "rank");
        String imageURL     = readText(parser);

        parser.require(XmlPullParser.END_TAG, ns, "rank");
        return imageURL;
    }

    private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
        String result = "";

        if (parser.next() == XmlPullParser.TEXT) {
            result = parser.getText();
            parser.nextTag();
        }
        return result;
    }


    private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            throw new IllegalStateException();
        }
        int depth = 1;
        while (depth != 0) {
            switch (parser.next()) {
            case XmlPullParser.END_TAG:
                depth--;
                break;
            case XmlPullParser.START_TAG:
                depth++;
                break;
            }
        }
     }
}

我现在遇到的问题是如何处理XML文件。特别是:如何读取XML文件以及如何让类为文件工作并将其打印到Android设备。非常感谢任何帮助。更确切地说,我有一个具有此布局的XML文件

<entry>
<rank>Rank 1</rank>
    <source><![CDATA[Der Postillon]]></source>
    <date>2013-09-24 15:11:48</date>
    <scores>
        <Flies>10797</Flies>
        <Facebook>10190</Facebook>
        <Twitter>345</Twitter>
        <GPlus>262</GPlus>
    </scores>
    <headline>Wikipedia löscht FDP-Eintrag wegen fehlender Relevanz</headline>
    <description>Berlin (dpo) - Das ging schnell. Seit gestern existiert der Wikipedia-Eintrag der FDP nicht mehr. Der mit knapp 10.000 Wörtern durchaus umfangreiche Beitrag wurde nach einer kurzen Löschdiskussion entfernt, weil er den strengen Relevanzkriterien des Online-Lexikons nicht mehr standhalten konnte. Für marginale Splitterparteien und Kleinstgruppierungen wie die Liberalen sei kein Platz in der Wikipedia. [Weiterlesen]</description>
    <articleURL>http://www.der-postillon.com/2013/09/wikipedia-loscht-fdp-eintrag-wegen.html</articleURL>
    <sourceURL><![CDATA[http://www.der-postillon.com]]></sourceURL>
    <imageURL><![CDATA[http://www.10000flies.de/images/nopic.jpg]]></imageURL>
</entry>

但我似乎没有找到一个很好的解决方案来处理这个问题。但我敢打赌,这非常容易。我找不到它。或者,您可以给我一个关于如何从本地文件夹中读取XML文件并使用它的简单教程。

1 个答案:

答案 0 :(得分:2)

如果你想从资产文件夹中获取xml文件,请使用下面的代码,

public void copyXMLFromAssets()
    {
        AssetManager assetManager = mActivity.getAssets();
        File AppDirectory = new File(Environment.getExternalStorageDirectory() + "/" + dirName);
        if (!AppDirectory.exists())
            {
                AppDirectory.mkdirs();
            }
                InputStream in = null;
                OutputStream out = null;
                try
                    {
                        in = assetManager.open(XML_name);
                        File outFile = new File(AppDirectory +"/"+XML_name);                                
                        out = new FileOutputStream(outFile);
                        copyFile(in, out);
                        in.close();
                        in = null;
                        out.flush();
                        out.close();
                        out = null;
                    }
                catch (IOException e)
                    {
                        Log.e("tag", "Failed to copy asset file: " + XML_name, e);
                    }

    }

然后使用以下代码从保存的位置读取此复制的XML文件

public InputStream GetStreamFromXmlFileOnSDCard()
        {
            File file = new File(Environment.getExternalStorageDirectory() +xml_path);
            InputStream istr = null;
            try
                {
                    istr = new FileInputStream(file);
                }
            catch (FileNotFoundException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            return istr;

        }

上面的函数返回xml文件的InputStream;您可以传递此InputStream来提取解析器并解析数据。