gpt4 book ai didi

java - 如何以编程方式从android中的url解析XML

转载 作者:行者123 更新时间:2023-12-01 07:48:17 27 4
gpt4 key购买 nike

我正在尝试解析来自 Magento for android 的 XML 格式响应我的回复如下:

XML 格式响应:

    <response>
<id>3</id>
<parent_id>1</parent_id>
<name>Arocos</name>
<is_active>true</is_active>
<position>2</position>
<level>1</level>
<product_count>35</product_count>
<children_data>
<item>
<id>5</id>
<parent_id>3</parent_id>
<name>DHOOP CONES</name>
<is_active>true</is_active>
<position>1</position>
<level>2</level>
<product_count>4</product_count>
<children_data/>
</item>
<item>
<id>6</id>
<parent_id>3</parent_id>
<name>SAMBRANI STEMS</name>
<is_active>true</is_active>
<position>2</position>
<level>2</level>
<product_count>2</product_count>
<children_data/>
</item>
</response>

我正在尝试使用 XML 解析器解析此响应,但我无法得到一些问题

公共(public)类 XMLParser {

public XMLParser() {

}

// Retrive XML from URL
public String getXmlFromUrl(String url) {
String xml = null;

try {
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;
}

// Retrive DOM element
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;
}

// Retrive Node 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 "";
}

// Retrive Node Value
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}

}

和我的主要 Activity :

public class MainActivity extends Activity {
// Declare Variables
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "item";
static String COUNTRY = "name";
static String POPULATION = "is_active";
static String FLAG = "flag";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadXML().execute();
}

// DownloadJSON AsyncTask
private class DownloadXML extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android XML Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}

@Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();

XMLParser parser = new XMLParser();
// Retrieve nodes from the given URL address
String xml = parser
.getXmlFromUrl("http://arocos.com/index.php/rest/V1/categories/");
// Retrive DOM element
Document doc = parser.getDomElement(xml);

try {
// Identify the element tag name
NodeList nl = doc.getElementsByTagName("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(RANK, parser.getValue(e, RANK));
map.put(COUNTRY, parser.getValue(e, COUNTRY));
map.put(POPULATION, parser.getValue(e, POPULATION));
map.put(FLAG, parser.getValue(e, FLAG));
// adding HashList to ArrayList
arraylist.add(map);
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}

请帮助我并指示我编写正确的编码...提前致谢..

最佳答案

使用 XmlPullParserFactory。

XmlPullParserFactory factory;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser responseParser = factory.newPullParser();
responseParser.setInput(new StringReader("Your Response"));
int eventType = responseParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.TEXT) {
if (responseParser.getText().equals("Your key to check")) {
//Your code
} else {
//Your code
}
}
eventType = responseParser.next();
}
} catch (XmlPullParserException | IOException e) {
e.printStackTrace();
} finally {
// Your code
}

唯一的条件是“您应该在字符串中得到响应”

关于java - 如何以编程方式从android中的url解析XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45056491/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com