我在使用 JDOM2 库(确切地说是 2.0.5)解析 Android 应用程序中的 XML 文件时遇到了问题。
在 Java 项目中,它工作正常,但在 Android 应用程序项目中,我收到以下消息:“无法打开http://jeancdc.perso.sfr.fr/fichierXML.xml ”
这是我的 XMLReader 类:
package fr.jcdc.exemple.jdom;
import java.io.IOException;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import android.util.Log;
public class XMLReader {
public XMLReader() {
super();
}
public void loading() {
try {
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build("http://jeancdc.perso.sfr.fr/fichierXML.xml");
Element rootNode = document.getRootElement();
List<Element> charactersList = rootNode.getChildren("personnage");
for (int i = 0; i < charactersList.size(); i++) {
Element node = (Element) charactersList.get(i);
Log.d("tag", node.getChildText("prenom") + " " + node.getChildText("nom"));
}
}
catch (IOException ioex) {
Log.d("ioex", ioex.getMessage());
}
catch (JDOMException jdomex) {
Log.d("jdomex", jdomex.getMessage());
}
}
}
我的主要课程:
package fr.jcdc.exemple.jdom;
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity {
private XMLReader xmlReader = new XMLReader();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xmlReader.loading();
}
}
这是我在日志中获得的异常跟踪的一部分:
06-24 22:58:39.794: D/ioex(18560): Couldn't open http://jeancdc.perso.sfr.fr/fichierXML.xml
06-24 22:58:39.794: W/System.err(18560): java.io.IOException: Couldn't open http://jeancdc.perso.sfr.fr/fichierXML.xml
06-24 22:58:39.864: W/System.err(18560): at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:755)
06-24 22:58:39.864: W/System.err(18560): at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:292)
06-24 22:58:39.864: W/System.err(18560): at org.jdom2.input.sax.SAXBuilderEngine.build(SAXBuilderEngine.java:217)
06-24 22:58:39.864: W/System.err(18560): at org.jdom2.input.sax.SAXBuilderEngine.build(SAXBuilderEngine.java:277)
06-24 22:58:39.864: W/System.err(18560): at org.jdom2.input.SAXBuilder.build(SAXBuilder.java:1141)
.....
06-24 22:58:39.864: W/System.err(18560): Caused by: android.os.NetworkOnMainThreadException
06-24 22:58:39.872: W/System.err(18560): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
06-24 22:58:39.872: W/System.err(18560): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
06-24 22:58:39.872: W/System.err(18560): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
06-24 22:58:39.880: W/System.err(18560): ... 20 more