难以使用xml pull解析器

时间:2012-08-02 11:21:22

标签: android xmlpullparser

我正在尝试解析xml文件:

<?xml version="1.0"?>
<root>
    <command>
        <word>cancel</word>
        <explanation>cancel print requested with lp</explanation>

    </command>
    <command>
        <word>cat file</word>
        <explanation>Display the file</explanation>

    </command>
</root>

我正在使用XML pull解析器。我的程序是

package com.example.androidsample2;

import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView myXmlContent = (TextView)findViewById(R.id.my_xml);
        String stringXmlContent;
        try {
            stringXmlContent = getEventsFromAnXML(this);
            myXmlContent.setText(stringXmlContent);
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private String getEventsFromAnXML(Activity activity)
    throws XmlPullParserException, IOException
    {
        StringBuffer stringBuffer = new StringBuffer();
        Resources res = activity.getResources();
        XmlResourceParser xpp = res.getXml(R.xml.xmlfile);
        xpp.next();
        int eventType = xpp.getEventType();
        String tag;
        while ((eventType = xpp.next()) != XmlPullParser.END_DOCUMENT)
        {
            if(XmlPullParser.START_TAG==eventType)
            {
                tag=xpp.getName();
                //stringBuffer.append("\n"+tag);
                if(tag=="word")
                {
                    eventType=xpp.next();
                    stringBuffer.append("\n"+xpp.getText().toString());
                }
            }

        }
        return stringBuffer.toString();

    }
}

如何使用“word”获取“解释”。如何使用“取消”获取“使用lp取消打印”?

1 个答案:

答案 0 :(得分:4)

以下行可能适用于C#但不适用于Java:

if(tag=="word")

相反,写一下:

if (tag.equals("word"))

<强>更新

String word = null;
while ((eventType = xpp.next()) != XmlPullParser.END_DOCUMENT)

    ...

    if (tag.equals("word"))
    {
        eventType = xpp.next();
        word = xpp.getText();
    }
    else if (tag.equals("explanation"))
    {
        eventType = xpp.next();
        if ("cancel".equals(word))
        {
            stringBuffer.append("\n" + xpp.getText());
        }
    }