#android #xml #dom #xml-parsing
#Android #xml #dom #xml-синтаксический анализ
Вопрос:
Хотя по этой теме есть много ресурсов, но я не могу найти ошибку в своем коде. у меня есть XML-файл по адресуhttp://omnicoders.in/test/new.xml Это была моя первая программа, поэтому я начал с парсера DOM.
вот код основного действия
package com.example.parsexml;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.TextView;
public class XMLMainActivity extends ActionBarActivity {
private static final String TAG = "XML parsing";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xmlmain);
TextView tv = (TextView) findViewById(R.id.tv_xml);
URL url;
try {
String urlAdd = getString(R.string.xmllink);
url = new URL(urlAdd);
URLConnection connection;
connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("root");
Element root = (Element) nl.item(0);
Element blub = (Element) root.getElementsByTagName("blub");
Element bar = (Element) root.getElementsByTagName("bar");
Element overflow = (Element) root
.getElementsByTagName("overflow");
String tag1 = blub.getNodeValue();
String tag2 = bar.getNodeValue();
String tag3 = overflow.getNodeValue();
String vinitxml = tag1 tag2 tag3;
tv.setText(vinitxml);
}
} catch (MalformedURLException e) {
Log.d(TAG, "MalformedURLException");
} catch (IOException e) {
Log.d(TAG, "IOException");
} catch (SAXException e) {
Log.d(TAG, "SAX Exception");
} catch (ParserConfigurationException e) {
Log.d(TAG, "Parse Configuration Excetion");
}
}
}
the string.xml это как
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ParseXml</string>
<string name="xmllink">http://omnicoders.in/test/new.xml</string>
<string name="action_settings">Settings</string>
</resources>
мой основной XML содержит только одно текстовое представление, и да, я также использовал разрешение Интернета в манифесте Android.
но мое приложение всегда останавливается и говорит, что, к сожалению, ваше приложение было остановлено.
Комментарии:
1. вы не можете запустить блокирующий вызов для потока пользовательского интерфейса
2. привет, не могли бы вы предоставить фрагмент кода для приведенной выше логики.
Ответ №1:
Попробуйте этот способ, надеюсь, это поможет вам решить вашу проблему.
private TextView tv_xml;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv_xml = (TextView) findViewById(R.id.tv_xml);
new GetXmlFromUrl().execute(getString(R.string.xmllink));
}
class GetXmlFromUrl extends AsyncTask<String, Void, String> {
URL url;
@Override
protected String doInBackground(String... params) {
String reponse="";
try {
url = new URL(params[0]);
URLConnection connection;
connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
connection.setRequestProperty("Content-Type", "text/xml");
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(in);
dom.getDocumentElement().normalize();
NodeList nodes = dom.getElementsByTagName("root");
for (int i = 0; i < nodes.getLength(); i ) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String tag1 = getValue("blub", element);
String tag2 = getValue("bar", element);
String tag3 = getValue("overflow", element);
reponse = tag1 " " tag2 " " tag3;
}
}
}
} catch (Throwable e) {
e.printStackTrace();
}
return reponse;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
tv_xml.setText(s);
}
}
private static String getValue(String tag, Element element) {
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}