【问题标题】:Converting a parsing tutorial into a project将解析教程转换为项目
【发布时间】:2014-04-03 20:17:10
【问题描述】:

我按照 youtube 上的教程将解析添加到 android 应用程序。在他的教程中,他解析了位于http://demoprojectserver1234.appspot.com/xmlquery.cgi?appid=3fa19507-c746-4dfa-8ded-ec60ef4d30d9 的从未关闭的记录标签内的数据。我想将此应用于我的项目并解析一些谷歌地图 api。 http://maps.googleapis.com/maps/api/distancematrix/xml?origins=Denver&destinations=Miami&language=en-EN&sensor=false 来自该 url 我想调整教程以捕获持续时间文本标签 1 天 5 小时的值以及距离文本标签 3,317 公里。

这是我完成教程后的主要活动课程。我知道我需要在 processReceivedData 方法中更改 if (tagName.equals("record") 到某些东西,但我不确定我是否会使用持续时间或文本,我不确定我是否会再做一个 if ( tagName.equals("record") 来捕获远处/文本,或者如果我使用文本,我可以让它成为一个循环来抓取它们。任何帮助指向正确方向以收集我所追求的值的任何帮助都是赞赏。

public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "ProjectServerDemo";

Button destination_next_button;
public final static String START_LOCATION = "com.google.gascalculator.START_LOCATION";
public final static String END_LOCATION = "com.google.gascalculator.END_LOCATION";
public static final String QUERY_URL = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins="
                    + START_LOCATION + "&destinations=" + END_LOCATION
                    + "&language=en-EN&sensor=false";



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    destination_next_button = (Button) findViewById(R.id.destination_next_button);
    destination_next_button.setOnClickListener(this);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private void destination_next_buttonClick() {
    Intent intent = new Intent(MainActivity.this, Vehicle.class);

    EditText startText = (EditText) findViewById(R.id.startinglocation);
    EditText endText = (EditText) findViewById(R.id.endinglocation);

    String startDestination = startText.getText().toString();
    String endDestination = endText.getText().toString();

    intent.putExtra(START_LOCATION, startDestination);
    intent.putExtra(END_LOCATION, endDestination);

    startActivity(intent);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.destination_next_button:
        destination_next_buttonClick();
        AsyncDownloader downloader = new AsyncDownloader();
        downloader.execute();

        break;
    }

}

private void handleNewRecord(String itemId, String data) {
    TextView textView = (TextView) findViewById(R.id.informationTextView);
    String message = 
            textView.getText().toString() + "\n" +
            itemId + ": " + data;
    textView.setText("");
}

private class AsyncDownloader extends AsyncTask<Object, String, Integer> {

    @Override
    protected Integer doInBackground(Object... arg0) {
        XmlPullParser receivedData = tryDownloadingXmlData();
        int recordsFound = tryParsingXMLData(receivedData);
        return recordsFound;
    }

    private XmlPullParser tryDownloadingXmlData() {
        try {
            URL xmlUrl = new URL(QUERY_URL);
            XmlPullParser receivedData = XmlPullParserFactory.newInstance().newPullParser();
            receivedData.setInput(xmlUrl.openStream(), null);
            return receivedData;
        } catch (XmlPullParserException e) {

        } catch (IOException e) {

        }
        return null;
    }

    private int tryParsingXMLData(XmlPullParser receivedData) {
        if (receivedData != null) {
            try {
                return processReceivedData(receivedData);
            } catch (XmlPullParserException e) {

            } catch (IOException e) {

            }   

        }
        return 0;
    }

    private int processReceivedData(XmlPullParser xmlData) throws XmlPullParserException, IOException {
        int recordsFound = 0;

        //find values in the xml records
        String appId = "";
        String itemId = "";
        String timeStamp = "";
        String data = "";

        int eventType = -1;
        while (eventType != XmlResourceParser.END_DOCUMENT) {
            String tagName = xmlData.getName();

            switch (eventType) {
            case XmlResourceParser.START_TAG:
                //start of a record so pull values encoded as attributes
                if (tagName.equals("record")) {
                    appId = xmlData.getAttributeValue(null, "appid");
                    itemId = xmlData.getAttributeValue(null, "itemid");
                    timeStamp = xmlData.getAttributeValue(null, "timestamp");
                    data = "";
                }
                break;

            //Grab data text (simple processing)
            //Note this could be full xml data to process
            case XmlResourceParser.TEXT:
                data += xmlData.getText();
                break;

            case XmlPullParser.END_TAG:
                if (tagName.equals("record")) {
                    recordsFound++;
                    publishProgress(appId, itemId, data, timeStamp);
                }
                break;
            }
            eventType = xmlData.next();
        }
        //handle no data available publish an empty event.
        if (recordsFound == 0) {
            publishProgress();
        }
        return 0;
    }

    @Override
    protected void onProgressUpdate(String... values) {

        if (values.length == 4) {
            String appId = values[0];
            String itemId = values[1];
            String data = values[2];
            String timestamp = values[3];

            handleNewRecord(itemId, data);

        }
        super.onProgressUpdate(values);
    }

}
}

【问题讨论】:

    标签: android xml-parsing


    【解决方案1】:

    您想存储您所在的当前节点,以便您可以编写“如果当前节点是 row.element.duration.value 然后将文本解析为持续时间值”。

    你可以这样做:

    private StringBuilder path = new StringBuilder();
    
    // (...)
    
    case XmlResourceParser.START_TAG:
        path.append('.').append(tagName);
    
    case XmlResourceParser.TEXT:
        String node = path.toString();
        if ("DistanceMatrixResponse.row.element.duration.value".equals(node) {
            // parse duration value
        } else if ("DistanceMatrixResponse.row.element.distance.value".equals(node) {
            // parse distance value
        } // etc...
    
    case XmlResourceParser.END_TAG:
        path.setLength(path.length() - tagName.length()); // remove tag name
        if (path.length() > 0)
            path.setLength(path.length() - 1); // remove trailing '.' 
    

    【讨论】:

      猜你喜欢
      • 2021-12-10
      • 1970-01-01
      • 2011-01-25
      • 2021-03-29
      • 2016-09-20
      • 1970-01-01
      • 2017-07-13
      • 2018-03-20
      • 1970-01-01
      相关资源
      最近更新 更多