我该如何解析这样的文件?

时间:2012-09-16 16:21:59

标签: java android xml parsing saxparser

我有一个问题,如果有人可以帮助我,那将是非常友好的:) 我试图解析这个XML文件:

   <data>
    <day>
        <match>

            <team1>foo</team1>
            <team2>foo</team2>

            <resultfinal></resultfinal>
            <result1></result1>
            <result2></result2>

            <venue>1</venue>
            <gmt>10:00</gmt>
            <groupe>B</groupe>

        </match>

        <match>

            <team1>foo</team1>
            <team2>foo</team2>

            <resultfinal></resultfinal>
            <result1></result1>
            <result2></result2>

            <venue>1</venue>
            <gmt>14:00</gmt>
            <groupe>A</groupe>

        </match>
    </day>

    <day>
        <match>

            <team1>foo</team1>
            <team2>foo</team2>

            <resultfinal></resultfinal>
            <result1></result1>
            <result2></result2>

            <venue>1</venue>
            <gmt>10:00</gmt>
            <groupe>B</groupe>

        </match>

        <match>

            <team1>foo</team1>
            <team2>foo</team2>

            <resultfinal></resultfinal>
            <result1></result1>
            <result2></result2>

            <venue>1</venue>
            <gmt>14:00</gmt>
            <groupe>A</groupe>

        </match>
    </day>

</data>

但我无法弄清楚如何实现这一目标。使用我的解析器,我可以解析这样的文件:

<data>
    <match>

        <team1>aust</team1>
        <team2>irl</team2>

        <resultfinal></resultfinal>
        <result1></result1>
        <result2></result2>

        <venue>1</venue>
        <gmt>10:00</gmt>
        <groupe>B</groupe>

    </match>

    <match>

        <team1>ind</team1>
        <team2>afg</team2>

        <resultfinal></resultfinal>
        <result1></result1>
        <result2></result2>

        <venue>1</venue>
        <gmt>14:00</gmt>
        <groupe>A</groupe>

    </match>
</data>

但我不知道如何存储每个<day>代码的数据。

我的XML处理程序如下所示:

@Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {

        if (localName.equalsIgnoreCase("team1"))
            data.setTeam1(elementValue);
        else if (localName.equalsIgnoreCase("team2"))
            data.setTeam2(elementValue);
        else if (localName.equalsIgnoreCase("resultfinal"))
            data.setResultfinal(elementValue);
        else if (localName.equalsIgnoreCase("result1"))
            data.setResult1(elementValue);
        else if (localName.equalsIgnoreCase("result2"))
            data.setResult2(elementValue);
        else if (localName.equalsIgnoreCase("date"))
            data.setDate(elementValue);
        else if (localName.equalsIgnoreCase("venue"))
            data.setVenue(elementValue);
        else if (localName.equalsIgnoreCase("gmt"))
            data.setGmt(elementValue);

    }

    @Override
    public void startElement(String uri, String localName, String qName,
            org.xml.sax.Attributes attributes) throws SAXException {
        // TODO Auto-generated method stub
        super.startElement(uri, localName, qName, attributes);
        elementOn = true;

        if (localName.equals("data")) {
            data = new XMLGettersSetters();
        } else if (localName.equals("match")) {

        }
    }

但是我可以只解析第二个文件。如何解析第一个文件以及如何存储数据?我无法将它存储在Arraylist中。

编辑:

我尝试像Don Roby建议的那样构建它,但我的应用程序总是崩溃。这是我到目前为止所做的:

MainActivity:

public class MainActivity extends Activity {
    XMLHandler data;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


try {
             Log.i("PARSER", "versuch!");

                /**
                 * Create a new instance of the SAX parser
                 **/

                SAXParserFactory saxPF = SAXParserFactory.newInstance();
                SAXParser saxP = saxPF.newSAXParser();
                XMLReader xmlR = saxP.getXMLReader();


                URL url = new URL("my xml file"); // URL of the XML

                /** 
                 * Create the Handler to handle each of the XML tags. 
                 **/
                 data = new XMLHandler();
                xmlR.setContentHandler(data);
                xmlR.parse(new InputSource(url.openStream()));


            } catch (Exception e) {
                System.out.println(e);
                Log.i("PARSER", "ES KLAPPT NICHT!");
            }




        TextView txt1 = (TextView) findViewById(R.id.txtview1);
        txt1.setText(data.getTournament().get(0).get(0).getTeam1().toString());

    }

XMLHandler:

public class XMLHandler extends DefaultHandler {

    private Tournament tournament;
    private TournamentDay currentDay;
    private Match currentMatch;
    private StringBuilder builder;

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {

        if (qName.equalsIgnoreCase("team1"))
            currentMatch.setTeam1(builder.toString());
        else if (qName.equalsIgnoreCase("team2"))
            currentMatch.setTeam2(builder.toString());
        else if (qName.equalsIgnoreCase("resultfinal"))
            currentMatch.setResultfinal(builder.toString());
        else if (qName.equalsIgnoreCase("result1"))
            currentMatch.setResult1(builder.toString());
        else if (qName.equalsIgnoreCase("result2"))
            currentMatch.setResult2(builder.toString());
        else if (qName.equalsIgnoreCase("venue"))
            currentMatch.setVenue(builder.toString());
        else if (qName.equalsIgnoreCase("gmt"))
            currentMatch.setGmt(builder.toString());
        else if (qName.equals("match"))
            currentDay.add(currentMatch);
        else if (qName.equals("day"))
            tournament.add(currentDay);
    }

    @Override
    public void startElement(String uri, String localName, String qName,
                             org.xml.sax.Attributes attributes) throws SAXException {
        if (qName.equals("data")) {
            tournament = new Tournament();
        }
        if (qName.equals("day")) {
            currentDay = new TournamentDay();
        }
        else if (qName.equals("match")) {
            currentMatch = new Match();
        }
        else {
            builder = new StringBuilder();
        }
    }

    @Override
    public void characters(char[] chars, int start, int length) throws SAXException {
        builder.append(chars, start, length);
    }

    public Tournament getTournament() {
        return tournament;
    }
}

赛:

public class Tournament {

    private List<TournamentDay> days;

    public Tournament() {
        this.days = new ArrayList<TournamentDay>();
    }

    public void add(TournamentDay day) {
        days.add(day);
    }
    public TournamentDay get(int i) {
       return days.get(i); 
    }
}

匹配

public class Match {
    private String team1;
    private String team2;
    private String resultfinal;
    private String result1;
    private String result2;
    private String date;
    private String venue;
    private String gmt;

    public String getTeam1() {
        return team1;
    }

    public void setTeam1(String team1) {
        this.team1 = team1;
    }

    public String getTeam2() {
        return team2;
    }

    public void setTeam2(String team2) {
        this.team2 = team2;
    }

    public String getResultfinal() {
        return resultfinal;
    }

    public void setResultfinal(String resultfinal) {
        this.resultfinal = resultfinal;
    }

    public String getResult1() {
        return result1;
    }

    public void setResult1(String result1) {
        this.result1 = result1;
    }

    public String getResult2() {
        return result2;
    }

    public void setResult2(String result2) {
        this.result2 = result2;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getVenue() {
        return venue;
    }

    public void setVenue(String venue) {
        this.venue = venue;
    }

    public String getGmt() {
        return gmt;
    }

    public void setGmt(String gmt) {
        this.gmt = gmt;
    }

}

最后是我的XML文件:

<data>
    <day>

        <match>

            <team1>ind</team1>
            <team2>afg</team2>

            <resultfinal></resultfinal>
            <result1></result1>
            <result2></result2>
            <date>19.09</date>
            <venue>1</venue>
            <gmt>14:00</gmt>


        </match>

        <match>

            <team1>eng</team1>
            <team2>afg</team2>

            <resultfinal></resultfinal>
            <result1></result1>
            <result2></result2>

            <date>21.09</date>
            <venue>1</venue>
            <gmt>14:00</gmt>


        </match>
        <match>

            <team1>ind</team1>
            <team2>eng</team2>

            <resultfinal></resultfinal>
            <result1></result1>
            <result2></result2>
            <date>23.09</date>
            <venue>2</venue>
            <gmt>10:00</gmt>


        </match>
    </day>
    <day>
        <match>

            <team1>aust</team1>
            <team2>irl</team2>

            <resultfinal></resultfinal>
            <result1></result1>
            <result2></result2>
            <date>19.08</date>
            <venue>1</venue>
            <gmt>10:00</gmt>


        </match>
        <match>

            <team1>aust</team1>
            <team2>west</team2>

            <resultfinal></resultfinal>
            <result1></result1>
            <result2></result2>
            <date>22.09</date>
            <venue>1</venue>
            <gmt>14:00</gmt>


        </match>
        <match>

            <team1>west</team1>
            <team2>irl</team2>

            <resultfinal></resultfinal>
            <result1></result1>
            <result2></result2>

            <date>24.09</date>
            <venue>1</venue>
            <gmt>14:00</gmt>


        </match>

    </day>

</data>

Edit2:这是logcat:

09-17 15:26:49.299: I/System.out(3392): java.lang.NullPointerException
09-17 15:26:49.299: I/PARSER(3392): ES KLAPPT NICHT!
09-17 15:26:49.299: D/AndroidRuntime(3392): Shutting down VM
09-17 15:26:49.299: W/dalvikvm(3392): threadid=1: thread exiting with uncaught exception (group=0xb40a64f0)
09-17 15:26:49.299: I/Process(3392): Sending signal. PID: 3392 SIG: 9
09-17 15:26:49.299: D/AndroidRuntime(3392): procName from cmdline: com.example.xmldownloader
09-17 15:26:49.299: E/AndroidRuntime(3392): in writeCrashedAppName, pkgName :com.example.xmldownloader
09-17 15:26:49.299: D/AndroidRuntime(3392): file written successfully with content: com.example.xmldownloader StringBuffer : ;com.example.xmldownloader
09-17 15:26:49.299: E/AndroidRuntime(3392): FATAL EXCEPTION: main
09-17 15:26:49.299: E/AndroidRuntime(3392): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.xmldownloader/com.example.xmldownloader.MainActivity}: java.lang.NullPointerException
09-17 15:26:49.299: E/AndroidRuntime(3392):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1698)
09-17 15:26:49.299: E/AndroidRuntime(3392):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1726)
09-17 15:26:49.299: E/AndroidRuntime(3392):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
09-17 15:26:49.299: E/AndroidRuntime(3392):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:949)
09-17 15:26:49.299: E/AndroidRuntime(3392):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-17 15:26:49.299: E/AndroidRuntime(3392):     at android.os.Looper.loop(Looper.java:130)
09-17 15:26:49.299: E/AndroidRuntime(3392):     at android.app.ActivityThread.main(ActivityThread.java:3770)
09-17 15:26:49.299: E/AndroidRuntime(3392):     at java.lang.reflect.Method.invokeNative(Native Method)
09-17 15:26:49.299: E/AndroidRuntime(3392):     at java.lang.reflect.Method.invoke(Method.java:507)
09-17 15:26:49.299: E/AndroidRuntime(3392):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880)
09-17 15:26:49.299: E/AndroidRuntime(3392):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:638)
09-17 15:26:49.299: E/AndroidRuntime(3392):     at dalvik.system.NativeStart.main(Native Method)
09-17 15:26:49.299: E/AndroidRuntime(3392): Caused by: java.lang.NullPointerException
09-17 15:26:49.299: E/AndroidRuntime(3392):     at com.example.xmldownloader.MainActivity.onCreate(MainActivity.java:58)
09-17 15:26:49.299: E/AndroidRuntime(3392):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
09-17 15:26:49.299: E/AndroidRuntime(3392):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1662)
09-17 15:26:49.299: E/AndroidRuntime(3392):     ... 11 more

3 个答案:

答案 0 :(得分:2)

一个好的做法是使用反映XML架构的对象模型。这样的事情:一个名为Day的对象,其中包含Collection Matches,其中包含8个字段(team1,team2,result1等)。

使用该模型,解析器必须做的就是在解析过程中构建对象。

此外,您还可以使用一些优秀的框架构建,只是为了将XML文件转换为Java对象,例如XStream

答案 1 :(得分:2)

Gilberto建议使对象模型反映XML模式是好的。

在我对您的域名的解释中,我创建了一个或多或少是Match的班级XMLGettersSetters,一个只包含Day的班级List<Match>,以及包含Tournament

的班级List<Day>

你当然可以将整个混乱表示为List<List<Match>>,但将它们封装在你自己的类中会更好一些。

我必须将您对localName的所有引用更改为使用qName,这可能只是反映了我的测试中的一个搞砸,但这大概有效并且应该让您了解如何处理此问题一种结构。

上面列出的类非常简单,但在这里它们是。

TournamentTournamentDay只是列表的包装:

public class Tournament {

    private List<TournamentDay> days;

    public Tournament() {
        this.days = new ArrayList<TournamentDay>();
    }

    public void add(TournamentDay day) {
        days.add(day);
    }
}

public class TournamentDay {

    private List<Match> matches;

    public TournamentDay() {
        this.matches = new ArrayList<Match>();
    }

    public void add(Match match) {
        matches.add(match);
    }
}

Matcher只是一个包含一堆String字段和setter的类。在实际使用中,您可能还需要getter,并且可能不希望所有字段都是字符串。

public class Match {
    private String gmt;
    private String team1;
    private String team2;
    private String venue;
    private String result1;
    private String result2;
    private String resultfinal;

    public void setGmt(String s) {
        gmt = s;
    }

    public void setVenue(String s) {
        venue = s;
    }

    public void setResult2(String s) {
        result2 = s;
    }

    public void setResult1(String s) {
        result1 = s;
    }

    public void setResultfinal(String s) {
        resultfinal = s;
    }

    public void setTeam2(String s) {
        team2 = s;
    }

    public void setTeam1(String s) {
        team1 = s;
    }
}

构建此结构的处理程序类应该看起来像这样,使用getTournament()方法在解析后检索结果。

public class TournamentHandler extends DefaultHandler {

    private Tournament tournament;
    private TournamentDay currentDay;
    private Match currentMatch;
    private StringBuilder builder;

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {

        if (qName.equalsIgnoreCase("team1"))
            currentMatch.setTeam1(builder.toString());
        else if (qName.equalsIgnoreCase("team2"))
            currentMatch.setTeam2(builder.toString());
        else if (qName.equalsIgnoreCase("resultfinal"))
            currentMatch.setResultfinal(builder.toString());
        else if (qName.equalsIgnoreCase("result1"))
            currentMatch.setResult1(builder.toString());
        else if (qName.equalsIgnoreCase("result2"))
            currentMatch.setResult2(builder.toString());
        else if (qName.equalsIgnoreCase("venue"))
            currentMatch.setVenue(builder.toString());
        else if (qName.equalsIgnoreCase("gmt"))
            currentMatch.setGmt(builder.toString());
        else if (qName.equals("match"))
            currentDay.add(currentMatch);
        else if (qName.equals("day"))
            tournament.add(currentDay);
    }

    @Override
    public void startElement(String uri, String localName, String qName,
                             org.xml.sax.Attributes attributes) throws SAXException {
        if (qName.equals("data")) {
            tournament = new Tournament();
        }
        if (qName.equals("day")) {
            currentDay = new TournamentDay();
        }
        else if (qName.equals("match")) {
            currentMatch = new Match();
        }
        else {
            builder = new StringBuilder();
        }
    }

    @Override
    public void characters(char[] chars, int start, int length) throws SAXException {
        builder.append(chars, start, length);
    }

    public Tournament getTournament() {
        return tournament;
    }
}

答案 2 :(得分:1)

尝试使用DOM parser,您可以完美访问Object Model tree的任何部分.....

如果您想要更多控制,请尝试下面提到的XML解析器....

- JAXP AND JAXB

- Castor