Unity Android 读取xml去除BOM

Unity打包WebGL之后保留了StreamingAssets文件夹,但是使用Application.streamingAssetsPath是无法读取到StreamingAssets文件路径的。为了能正确读取到本地StreamingAssets文件的数据,我们需要使用到UnityWebRequest类。

System.Uri这个类,这个类可以帮助我们更好的构造uri,特别是在使用本地路径得时候,结合Path.Combine能更好的得出Uri路径。因为平台的区别,Uri路径也不同:
Windows平台 file:///D:/DATA/StreamingAssets/data.json
WebGl平台 http://localhost/StreamingAssets/data.json
Android平台 jar:file:///data/app/xxx!/assets/data.json
iOS平台 Application/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/xxx.app/Data/Raw

使用Path.Combine拼接路径字符串
var uri = new System.Uri(Path.Combine(Application.streamingAssetsPath,
“.xml”));
var filePath = new System.Uri(Path.Combine(Application.streamingAssetsPath, “Settings.xml”)) ;
UnityWebRequest request = UnityWebRequest.Get(filePath);
yield return request.SendWebRequest();
if (request.result!=UnityWebRequest.Result.Success)
{
UnityEngine.Debug.LogError("Failed to download XML file: " + request.error);
yield break;
}
else
{
byte[] responseData = request.downloadHandler.data;
responseData=RemoveBom(responseData);//移除BOM
string xmlData = Encoding.UTF8.GetString(responseData);
XmlDocument doc= new XmlDocument();
doc.LoadXml(xmlData);
XmlNodeList nodeList = doc.GetElementsByTagName(“noci”);

        foreach (XmlNode node in nodeList)
        {
            if ("ReceivePLC" == node.Attributes["key"].Value)
            {
                receiveIp = node.Attributes["receiveIp"].Value;
                receivePort = int.Parse(node.Attributes["receivePort"].Value);
            }
        }

private byte[] RemoveBom(byte[] data)
{
// UTF-8 的 BOM 字节序列为 EF BB BF
byte[] bom = new byte[] { 0xEF, 0xBB, 0xBF };

    if (data.Length >= bom.Length && data[0] == bom[0] && data[1] == bom[1] && data[2] == bom[2])
    {
        byte[] result = new byte[data.Length - bom.Length];
        Array.Copy(data, bom.Length, result, 0, result.Length);
        return result;
    }

    return data;
}

xml 修改后保存路径doc.Save(uri.AbsolutePath)

猜你喜欢

转载自blog.csdn.net/weixin_43780907/article/details/130763661