我想从URL读取XML数据并尝试过不同的方式。但无法找到答案。我开发了一个agumented reality应用程序,iam从XML读取位置信息(在URL中)
Iam新蜜蜂到了安卓手机
我有以下XML数据。
<specialoffers>
<categories>
<category>
<![CDATA[ 0% Installment Payment Plan Offers ]]>
</category>
<merchants>
<merchantname>
<![CDATA[ EmaxIPP ]]>
</merchantname>
<merchantbigimage>
<![CDATA[
http://www.XXX.com/Images/Emax%20New%20-%20190x73-1_tcm20-48180.jpg
]]>
</merchantbigimage>
<merchantsmallimage>
<![CDATA[
http://www.XXX.com/Images/Emax%20New%20-%20104x75-1_tcm20-48179.jpg
]]>
</merchantsmallimage>
<merchantmobileimage>
<![CDATA[ http://www.XXX.com ]]>
</merchantmobileimage>
<mobilehighlight>
<![CDATA[
Enjoy 0% Installment Payment Plan for 3 months on
all purchases made </b>
]]>
</mobilehighlight>
<highlight>
<![CDATA[
Enjoy 0% Installment Payment Plan for 3 months on all purchases
made with your </b>
]]>
</highlight>
<locations>
<location>
<emirate>
<![CDATA[ XXX]]>
</emirate>
<address>
<![CDATA[ Center 1 ]]>
</address>
<latitude>
<![CDATA[ 51.169601 ]]>
</latitude>
<longitude>
<![CDATA[ 61.240395 ]]>
</longitude>
</location>
</merchants>
</categories>
</specialoffers>
这是代码......
AndroidXMLParsingActivity.java
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://www.adcb.com/specialoffers-test.xml";
// XML node keys
static final String KEY_ITEM = "categories"; // parent node
static final String KEY_ID = "category";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> menuItems =
new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// 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_ID, parser.getValue(e, KEY_ID));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_ID, "KEY_DESC", "100" }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView)
view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView)
view.findViewById(R.id.cost)).getText().toString();
String description = ((TextView)
view.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(KEY_ID, name);
in.putExtra("100", cost);
in.putExtra("KEY_DESC", description);
startActivity(in);
}
});
}
}
XMLParser.java
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* @param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* @param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* @param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child =
child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* @param Element node
* @param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
SingleMenuItemActivity.java
public class SingleMenuItemActivity extends Activity {
// XML node keys
static final String KEY_ID = "category";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String name = in.getStringExtra(KEY_ID);
String cost = in.getStringExtra(KEY_COST);
String description = in.getStringExtra(KEY_DESC);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.cost_label);
TextView lblDesc = (TextView) findViewById(R.id.description_label);
lblName.setText(name);
lblCost.setText(cost);
lblDesc.setText(description);
}
}
答案 0 :(得分:0)
您可以像这样使用xmlpullparser:
XmlPullParserFactory pullParserFactory;
try {
pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
我找到了一个根据您的需要展示相同示例的链接。请仔细阅读link
或者只是去android方式。开发人员指南link
希望它对你有所帮助。
答案 1 :(得分:0)
对于Android使用SimpleXml xml解析API,它将使您的编码变得容易。