我尝试用XML解析网页并在我的logcat中打印数据,但我的输出是空的。 这是我的XML结构:
<?xml version="1.0"?>
<FLIGHTS>
<FLIGHT airport="b: 3 "
logo="IG"
code="IG"
numero="1234"
carrier="AirBerlin"
city="NEW YORK"
terminal="Terminal A"
sched="08:40"
expect="09:09"
tipo_volo="L" stato="J"
</FLIGHT>
<FLIGHT airport="c: 3 "
....
.....more...
</FLIGHT>
</FLIGHTS>
这是我在AsyncTask中的Android代码:
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL("http://myurl");
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
NodeList nodes = doc.getElementsByTagName("FLIGHT");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
// NodeList title = element.getElementsByTagName("airport");
// Element line = (Element) title.item(0);
// a.add(line.getTextContent());
Log.d("LOG...", "" + element.getTextContent());
}
} catch (Exception e) {
e.printStackTrace();
}
在AndroidManifest中,我有互联网许可!
谢谢!
答案 0 :(得分:1)
如果XML是正确的,那么属性XXX="..."
会有所不同:
Element element = (Element) nodes.item(i);
String airport = element.getAttribute("airport");
if (airport != null) { ...
答案 1 :(得分:0)
您的代码示例有效。 Java区分大小写。您确定您的XML标记名称是否正确?
这是一个使用w3schools的XML示例的工作示例:
NO_BUILD=true python setup.py
现在使用您的XML示例和Joop Eggen's回答:
try {
URL url = new URL("http://www.w3schools.com/xml/note.xml");
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
NodeList nodes = doc.getElementsByTagName("note");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
// NodeList title = element.getElementsByTagName("airport");
// Element line = (Element) title.item(0);
// a.add(line.getTextContent());
System.out.println(element.getTextContent());
}
} catch (Exception e) {
e.printStackTrace();
}
使用简单文件的示例:
的test.xml:
try {
URL url = new URL("http://myurl");
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
NodeList nodes = doc.getElementsByTagName("FLIGHT");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
String airport = element.getAttribute("airport");
System.out.println("element " + i + ": airport=" + airport);
}
} catch (Exception e) {
e.printStackTrace();
}
Example.java:
<?xml version="1.0"?>
<FLIGHTS>
<FLIGHT airport="b: 3 " logo="IG" code="IG" numero="1234"
carrier="AirBerlin" city="NEW YORK" terminal="Terminal A" sched="08:40"
expect="09:09" tipo_volo="L" stato="J">
</FLIGHT>
</FLIGHTS>