我有一个XML解析器完美的作品,当我从文件加载:问题解析来自一个字符串的XML,但没有一个文件
private void getParsedXML(int id, Context context) throws Exception {
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();
/* Create a new ContentHandler and apply it to the XML-Reader */
XMLHandlerLevel myExampleHandler = new XMLHandlerLevel();
xr.setContentHandler(myExampleHandler);
/* Load xml file from raw folder*/
InputStream in = context.getResources().openRawResource(id);
/* Begin parsing */
xr.parse(new InputSource(in));
this.levelData = myExampleHandler.getLevelData();
in.close();
}
但现在我也得到索姆内容形成一个服务器。 XML是再发送一个字符串,这是它的块:
private void getParsedXML(String s) throws Exception{
if(this.levelData == null){
InputStream in = StringToStream(s);
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLHandlerLevel myExampleHandler = new XMLHandlerLevel();
XMLReader xr = sp.getXMLReader();
/* Begin parsing */
xr.parse(new InputSource(in));
this.levelData = myExampleHandler.getLevelData();
Log.e("jason",(levelData!=null)?levelData.toString():null);
in.close();
}
}
这里是StringToString功能
public static InputStream StringToStream(String text) {
InputStream is = null;
/*
* Convert String to InputStream using ByteArrayInputStream
* class. This class constructor takes the string byte array
* which can be done by calling the getBytes() method.
*/
try {
is = new ByteArrayInputStream(text.getBytes("UTF-8"));
is.reset();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e){
Log.e("jason","failed again");
}
return is;
}
但是,这并不工作...
我确定String的内容。 和我测试了StringToStream函数,它工作正常。
我也把日志放在XMLHandlerLevel来检查发生了什么,没有函数startDocument()甚至没有调用,但我没有得到任何错误消息没有例外,所以我完全失去了解释这一点。
继续: 当XML来自context.getResources()。openRawResource(id); 但不是当它形成一个字符串 为什么?
感谢您的任何想法
杰森
你是什么意思,它不工作?抛出异常吗? – kgiannakakis 2011-04-14 11:31:44
你没有把文本变成InputStream,StringReader会更好。但是,解码代码基本相同 - 必须有其他错误?在这样的情况下,使解析方法采用xml源代码,以使工作和非工作代码共享一些逻辑,以便您可以消除共享代码作为问题。 – ThomasRS 2011-04-14 11:34:54
@kgiannakakis没有异常抛出这是最令我讨厌的东西。 @Thomas tis已经做了我所做的唯一的区别是在InputSource上创建 – 2011-04-14 12:06:54