Java/Android中解析xml文件,可以使用DOM的API。
如 读取xml中的值可以是:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try{
DocumentBuilder builder = dbf.newDocumentBuilder();
Log.d(TAG, "----onkeyDown # 1----");
//String path = "file:///data/data/com.example.androiddemo/network.xml";
//Document doc = builder.parse("/data/data/com.example.androiddemo/network.xml");
String path = "file:///data/data/com.example.androiddemo/network.xml";
Document doc = builder.parse(path);
Log.d(TAG, "----onkeyDown # 2----");
NodeList nl = doc.getElementsByTagName("people");
for(int i=0; i<nl.getLength(); i++){
Element node = (Element)nl.item(i);
String name = node.getNodeName();
String value = node.getNodeValue();
System.out.println("name : "+name+", value : "+value);
}
}catch(Exception ex){
ex.printStackTrace();
}
奇怪的是,在window中使用String path = "network.xml"; 可以正常解析。但在Android模拟器和机器上那个调试,却总是报
01-19 15:20:37.211: W/System.err(1050): java.net.MalformedURLException: Protocol not found: data/data/com.example.androiddemo/network.xml
01-19 15:20:37.281: W/System.err(1050): at java.net.URL.<init>(URL.java:178)
01-19 15:20:37.281: W/System.err(1050): at java.net.URL.<init>(URL.java:127)
01-19 15:20:37.281: W/System.err(1050): at org.apache.harmony.xml.parsers.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:115)
01-19 15:20:37.291: W/System.err(1050): at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:155)
01-19 15:20:37.291: W/System.err(1050): at com.example.androiddemo.MainActivity.onKeyDown(MainActivity.java:41)
01-19 15:20:37.291: W/System.err(1050): at android.view.KeyEvent.dispatch(KeyEvent.java:2551)
01-19 15:20:37.291: W/System.err(1050): at android.app.Activity.dispatchKeyEvent(Activity.java:2329)
01-19 15:20:37.302: W/System.err(1050): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1806)
的错误。错误注意第一行,说是protocol not found。
解决方法是使用file类型协议,如
String path = "file:///data/data/com.example.androiddemo/network.xml";
然后调用
Document doc = builder.parse(path);
解析,返回Document类型数据。搞定!