【问题标题】:Issues with reading XML file from StreamingAssets on Android从 Android 上的 StreamingAssets 读取 XML 文件的问题
【发布时间】:2017-02-10 03:56:28
【问题描述】:

我遇到了一个问题,即我无法从 StreammingAssets 文件夹中的 XML 文件中读取数据。在编辑器上一切正常,但在 Android 上却不行。

     public void Start () {
     Type[] itemTypes = { typeof(Equipment), typeof(Weapon), typeof(Consumeble), typeof(Jevelary) };
     XmlSerializer serializer = new XmlSerializer(typeof (ItemContainer), itemTypes);
     TextReader textReader = new StreamReader (Application.streamingAssetsPath + "/" + "Items.xml");
     itemContainer = (ItemContainer)serializer.Deserialize (textReader);
     textReader.Close ();
 }

我确定问题出在这一行:

 TextReader textReader = new StreamReader (Application.streamingAssetsPath + "/" + "Items.xml");

我不知道如何解决它。 提前致谢。

【问题讨论】:

  • 谷歌搜索 logcat。了解如何使用它。由于彩色文本和过滤,我喜欢在 android studio 中使用它。然后重现您的问题,同时保持对您的 logcat 的关注。在此处发布您的例外情况,以便我们为您提供帮助。

标签: c# android xml unity3d xml-serialization


【解决方案1】:

您可能需要使用 file:/// 前缀作为 android 的路径。

尝试调试您传递给 StreamReader 的路径,然后尝试使用该路径从浏览器打开该文件。

你可以像程序员所说的那样,使用 www 类。

#if UNITY_ANDROID
   WWW www = new WWW( "file:///" + Application.streamingAssetsPath + "/Items.xml");
#elif UNITY_EDITOR
    //your previous code which worked in the editor
#endif

【讨论】:

    【解决方案2】:

    它是StreamingAssets 而不是StreammingAssets。像these 这样的特殊文件夹区分大小写,必须拼写正确才能按预期工作。只需更正拼写即可。如果可能,直接从此处复制名称 (StreamingAssets) 并将其粘贴到编辑器中。也许这是您问题中的错字?

    主要问题出在这里:

    TextReader textReader = new StreamReader (Application.streamingAssetsPath + "/" + "Items.xml");
    

    不能使用StreamReaderStreamingAssets 文件夹中读取数据。您必须使用 WWW 在 Android 中执行此操作。不确定这是否也适用于 iOS。

    1。使用WWW 类从StreamingAssets 文件夹中读取xml 文件。

    2.从字符串WWW读取创建新的StringReader实例。

    3.从StringReader 实例创建新的TextReader

    void Start()
    {
        StartCoroutine(readXML());
    }
    
    IEnumerator readXML()
    {
        Type[] itemTypes = { typeof(Equipment), typeof(Weapon), typeof(Consumeble), typeof(Jevelary) };
        XmlSerializer serializer = new XmlSerializer(typeof(ItemContainer), itemTypes);
    
        WWW www = new WWW(Application.streamingAssetsPath + "/" + "Items.xml");
        yield return www;
    
        if (string.IsNullOrEmpty(www.error))
        {
            string result = www.text;
            TextReader textReader = new StringReader(result);
    
            itemContainer = (ItemContainer)serializer.Deserialize(textReader);
            textReader.Close();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2013-07-09
      • 2013-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多