Android XML parse failed Unexpected token

眉间皱痕 提交于 2019-12-01 22:15:43

问题


In my app(game), i need to read a XML script and turn in into a class object; i've completed the entire XML reader via DOM

but when i run , i got the following error:

05-08 23:03:22.342: I/System.out(588): XML Pasing Excpetion = org.xml.sax.SAXParseException: Unexpected token (position:TEXT ��������������������...@1:69 in java.io.InputStreamReader@4129a200) 

i've read some answers about this but they all failed to fix my problem (http://stackoverflow.com/questions/7885962/android-utf-8-file-parsing)..

here's my code:

    InputStream inputStream = ctx.getResources().openRawResource(R.xml.script);
ctx.getApplicationContext().getPackageName()+"/xml/"+path);



        Reader reader = new InputStreamReader(inputStream,"UTF-8");

        InputSource is = new InputSource(reader);
        is.setEncoding("UTF-8");


        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();


        Document root = db.parse(is);

according to the problem, i've also tried this to:

 InputStream inputStream = ctx.getResources().openRawResource(R.xml.script);
 Document root = db.parse(inputStream);

which produced exactly the same exceptions...

how to solve this problem?

my xml file:

<script>

<scene no="0">
    <character id="1">1</character>

    <dialog no="1">
        <title>1</title>
 Sub-Element 1
    </dialog>
</scene>



</script>

回答1:


Your XML is invalid. "Sub-Element 1" should be within an element itself. XML-documents should also begin with a tag defining it as XML: <?xml version="1.0" ?> So your complete file would be:

<?xml version="1.0" ?>
<script>
<scene no="0">
    <character id="1">1</character>
    <dialog no="1">
        <title>1</title>
        <something_else>Sub-Element 1</something_else>
    </dialog>
</scene>
</script>

Or you could use "Sub-Element" as the element name (instead of something_else) and 1 as the value.




回答2:


Where do you store your xml file? In "res" folder. You should store it in "assets". Res-solution is not working because of specific of the "res" folder and it's presentation in the apk. Move your file to the "assets" and you'll see that everything is working. Use the following code for creating InputSource

getAssets().open("yourfilename.xml")


来源:https://stackoverflow.com/questions/10501426/android-xml-parse-failed-unexpected-token

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!