问题
Here is my RSS feed im trying to parse
<PetrolPrices>
<Fuel type="Unleaded">
<Highest units="p">132.9</Highest>
<Average units="p">128.8</Average>
<Lowest units="p">125.9</Lowest>
</Fuel>
<Fuel type="Diesel">
<Highest units="p">137.9</Highest>
<Average units="p">132.4</Average>
<Lowest units="p">129.7</Lowest>
</Fuel>
<Fuel type="Super Unleaded">
<Highest units="p">142.9</Highest>
<Average units="p">137.7</Average>
<Lowest units="p">132.9</Lowest>
</Fuel>
<Link>
http://www.petrolprices.com/search.html?search=Glasgow
</Link>
</PetrolPrices>
the problem is this is very different from any xml ive ever parsed i mean most of the time its a simple
<title>
"The Title"
</title>
My question is which what are the tag names i should be using and also how is it possible to get the fuel tag since its used when im trying to get the other tags. Basically i want it parsed like below
Type is = "Unleaded
Highest units = 132.9
Average units = 128.8
Lowest units = 125.9
*after all other tags are done
link = http://www.petrolprices.com/feeds/averages.xml?search_type=town&search_value=glasgow
Edit: this is the code i use to parse the data
package org.me.myandroidstuff;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
//import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
//import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class PetrolPriceActivity extends ListActivity
{
static final String KEY_FUEL = "Fuel"; // parent node
static final String KEY_TYPE = "type";
static final String KEY_HIGHEST = "Highest";
static final String KEY_AVERAGE = "Average";
static final String KEY_LOWEST = "Lowest";
private TextView errorText;
private String petrolPriceURL;
private static final String TAG = "PetrolPrice";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
Bundle extras = getIntent().getExtras();
if(extras!=null){
petrolPriceURL =extras.getString("URLString");
}
// Get the TextView object on which to display the results
new asyncTask().execute(petrolPriceURL);
}
// End of onCreate
public class asyncTask extends AsyncTask<String, Integer, ArrayList<HashMap<String, String>>>
{
ArrayList<HashMap<String, String>> menuItems;
ProgressDialog dialog = new ProgressDialog(PetrolPriceActivity.this);
@Override
protected void onPreExecute()
{
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.setMax(100);
dialog.setMessage("loading...");
dialog.show();
}
@Override
protected ArrayList<HashMap<String, String>> doInBackground(String...params)
{
for(int i = 0; i < 100; i++)
{
publishProgress(1);
try
{
Thread.sleep(50);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String urlString = petrolPriceURL;
String result = "";
InputStream anInStream = null;
int response = -1;
URL url = null;
try
{
url = new URL(urlString);
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
return null;
}
URLConnection conn = null;
try
{
conn = url.openConnection();
}
catch (IOException e)
{
// TODO Auto-generated catch block
return null;
}
// Check that the connection can be opened
if (!(conn instanceof HttpURLConnection))
{
try
{
throw new IOException("Not an HTTP connection");
}
catch (IOException e)
{
// TODO Auto-generated catch block
return null;
}
}
try
{
// Open connection
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
// Check that connection is OK
if (response == HttpURLConnection.HTTP_OK)
{
// Connection is OK so open a reader
anInStream = httpConn.getInputStream();
InputStreamReader in= new InputStreamReader(anInStream);
BufferedReader bin= new BufferedReader(in);
// Read in the data from the RSS stream
String line = new String();
while (( (line = bin.readLine())) != null)
{
result = result + line;
}
}
menuItems = new ArrayList<HashMap<String, String>>();
Handler parser = new Handler();
String xml = result; // getting XML
Document doc = parser.getDomElement(xml);
// getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_FUEL);
Log.v(TAG, "index=" + nl.getLength());
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++)
{
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TYPE, parser.getValue(e, KEY_TYPE));
map.put(KEY_HIGHEST, "Highest units = " + parser.getValue(e, KEY_HIGHEST));
map.put(KEY_AVERAGE, "Average units = " + parser.getValue(e, KEY_AVERAGE));
map.put(KEY_LOWEST, "Lowest units = " +parser.getValue(e, KEY_LOWEST));
// adding HashList to ArrayList
menuItems.add(map);
Log.v(TAG, "index1=" + menuItems);
}
}
catch (IOException ex)
{
try
{
throw new IOException("Error connecting");
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return menuItems;
}
@Override
protected void onProgressUpdate(Integer...progress)
{
dialog.incrementProgressBy(progress[0]);
}
@Override
protected void onPostExecute(ArrayList<HashMap<String,String>> menuItems)
{
errorText = (TextView)findViewById(R.id.error);
TextView linkView = (TextView)findViewById(R.id.link);
try
{
//Get the data from the RSS stream as a string
ListAdapter adapter = new SimpleAdapter(PetrolPriceActivity.this, menuItems,
R.layout.list_content,
new String[] { KEY_TYPE, KEY_HIGHEST, KEY_AVERAGE, KEY_LOWEST}, new int[] {
R.id.fuel, R.id.highest, R.id.average, R.id.lowest});
Log.v(TAG, "index2=" + menuItems);
setListAdapter(adapter);
}
catch(Exception ae)
{
// Handle error
// Add error info to log for diagnostics
errorText.setText(ae.toString());
}
linkView.setText(petrolPriceURL);
Log.v(TAG, "indexppu=" + petrolPriceURL);
if(dialog.getProgress() == dialog.getMax())
dialog.dismiss();
}
}
// End of petrolPriceString
// End of Activity class
}
回答1:
Try this..
Use XMLPullParser
try {
URL url = new URL(
"http://www.petrolprices.com/feeds/averages.xml?search_type=town&search_value=glasgow");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("Fuel");
for (int i = 0; i < nodeList.getLength(); i++) {
Element nameElement1 = (Element) nodeList.item(i);
System.out.println("type : "+ nameElement1.getAttribute("type")); // Here we are getting type Attribute Value
Toast.makeText(getBaseContext(), "type = "
+ nameElement1.getAttribute("type"), Toast.LENGTH_SHORT).show();
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("Highest");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
Toast.makeText(getBaseContext(), "Highest = "
+ ((Node) nameList.item(0)).getNodeValue(), Toast.LENGTH_SHORT).show();
Log.v("Highest--", ((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("Average");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
Log.v("Average--", ((Node) websiteList.item(0)).getNodeValue());
websiteList = fstElmnt.getElementsByTagName("Lowest");
websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
Log.v("Lowest--", ((Node) websiteList.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
EDIT
Change this..
map.put(KEY_TYPE, parser.getValue(e, KEY_TYPE));
to
map.put(KEY_TYPE, e.getAttribute(KEY_TYPE));
来源:https://stackoverflow.com/questions/25387332/androidtags-for-rss-feed-parsing