如何将转换字符串写入Document对象

时间:2012-12-20 15:01:44

标签: android xml-parsing sax android-xml saxparseexception

我有一个字符串,其中包含xml内容,如下所示:

String xml = "<item_list>" +
                "<category id='2' name='categoryName'>" +
                   "<item id='41' name='item1' />" +
                "</category>" +
             "</item_list>)";

我想将其转换为Document对象。这是我的代码:

Document doc = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
StringReader sr = new StringReader(xml);
InputSource is = new InputSource(sr);
doc = builder.parse(is);

当我运行时,我得到下一个错误:

org.xml.sax.SAXParseException: Unexpected token (position:TEXT )@1:139 in java.io.InputStreamReader@40fa7860)

我做错了什么?

2 个答案:

答案 0 :(得分:2)

将您的xml字符串更改为:

String xml = "<?xml version='1.0' encoding='UTF-8'?>" +
                "<item_list>" +
                "<category id='2' name='categoryName'>" +
                   "<item id='41' name='item1' />" +
                "</category>" +
             "</item_list>";

目前您在字符串

中缺少xml文档标题<?xml version='1.0' encoding='UTF-8'?>

有关我们如何在android中创建xml doc的更多帮助,请参阅本教程:

http://xjaphx.wordpress.com/2011/10/27/android-xml-adventure-create-write-xml-data/

答案 1 :(得分:0)

"</item_list>)";

那个括号不应该存在。