【问题标题】:Android XML parse failed Unexpected tokenAndroid XML解析失败意外令牌
【发布时间】:2012-05-17 02:28:00
【问题描述】:

在我的应用程序(游戏)中,我需要读取一个 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>

【问题讨论】:

    标签: android xml sax


    【解决方案1】:

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

    <?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 作为值。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2023-03-27
        • 2019-02-15
        • 2021-04-26
        • 2021-05-01
        • 2020-11-16
        • 2021-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多