2012-01-12 45 views
1

XML解析的问题,我尝试从str这个方法解析XML:在Java的Android

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
DocumentBuilder db = dbf.newDocumentBuilder();  
InputSource is = new InputSource();  
is.setCharacterStream(new StringReader(str.toString()));  
Document doc = db.parse(is); 

str我有:

<foo><bar>baz</bar></foo> 

但总是db.parse(is);应用是崩溃。 但如果我把代替:

is.setCharacterStream(new StringReader(str.toString())); 

这样的:

is.setCharacterStream(new StringReader("<foo><bar>baz</bar></foo>")); 

它的工作完美。任何想法?

+2

什么excatly是“应用程序是死机”?有什么异常? – 2012-01-12 22:31:48

+0

org.xml.sax.SAXParseException:意外令牌(位置:TEXT @ 1:2 [email protected]) – MTA 2012-01-12 22:44:45

+0

你确定乙方拥有该XML字符串?你打印了吗?如果str真的存在,我会将str.toString()更改为str.toString()。trim();并尝试。 – kosa 2012-01-12 22:59:03

回答

0

我不知道什么是str。如果海峡已经是一个字符串,则不需要使用str.toString

或者如果str是任何TextView或EditText,则使用str.getText()。toString.Then它将工作。并且如果您有第三种情况,尽管这两个请指定这个以便我可以编辑我的答案

0


我建议你改用SAX XML解析器而非DOM解析器。因为它更快,使用更少的内存并且更容易实现(Dnt认为使用像STAX这样的高级解析器,因为它们在android中不受支持)。检查此链接了ANDROID: Parsing XML