【发布时间】:2014-08-23 05:18:41
【问题描述】:
虽然有很多关于这个主题的资源,但我无法找出我的代码中的错误。我在位置 http://omnicoders.in/test/new.xml 有一个 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");
}
}
}
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 manifest 中使用了互联网权限。
但我的应用程序总是停止并说很遗憾您的应用程序已停止。
【问题讨论】:
-
你不能运行对 UI 线程的阻塞调用
-
你好,你能提供上面逻辑的代码sn-p吗?
标签: android xml dom xml-parsing