2

我正在尝试解析 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 拉解析器。我的程序是

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”获得“解释”。即如何使用“cancel”获得“cancel print requests with lp”?

4

1 回答 1

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());
        }
    }
于 2012-08-02T11:29:05.153 回答