3

在我的应用程序(游戏)中,我需要读取一个 XML 脚本并变成一个类对象;我已经通过 DOM 完成了整个 XML 阅读器

但是当我运行时,出现以下错误:

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) 

我已经阅读了一些关于此的答案,但它们都未能解决我的问题(http://stackoverflow.com/questions/7885962/android-utf-8-file-parsing)..

这是我的代码:

    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);

根据问题,我也试过这个:

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

这产生了完全相同的异常......

如何解决这个问题呢?

我的 xml 文件:

<script>

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

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



</script>
4

2 回答 2

6

您的 XML 无效。“子元素 1”应该在元素本身内。XML 文档还应该以将其定义为 XML 的标记开头:<?xml version="1.0" ?>因此您的完整文件将是:

<?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>

或者您可以使用“子元素”作为元素名称(而不是something_else)和 1 作为值。

于 2012-05-08T15:19:55.160 回答
3

你在哪里存储你的 xml 文件?在“res”文件夹中。您应该将其存储在“资产”中。由于特定的“res”文件夹及其在 apk 中的介绍,Res-solution 不起作用。将您的文件移动到“资产”,您会看到一切正常。使用以下代码创建 InputSource

getAssets().open("yourfilename.xml")
于 2013-02-18T13:18:47.097 回答