kingBook

导航

unity UTF8格式加载和保存xml

UTF8格式加载xml

string xmlPath="D:/xxx.xml"
FileLoader fileLoader=new FileLoader();
fileLoader.loadAsync(xmlPath);
fileLoader.onComplete-=onloadXmlComplete;

private void onloadXmlComplete(byte[][] bytesList){
	fileLoader.onComplete-=onloadXmlComplete;
	byte[] bytes=bytesList[0];
	if(bytes!=null){
		string xmlString=System.Text.Encoding.UTF8.GetString(bytes);
		xmlDocument=new XmlDocument();
		xmlDocument.LoadXml(xmlString);
	}
}

UTF8格式保存xml

xmlDocument.Save("D:/xxx.xml");

FileLoader.cs

using System;
using System.IO;
using System.Threading.Tasks;
using UnityEngine;

/// <summary>
/// 文件加载器
/// </summary>
public class FileLoader{
	
	/// <summary>
	/// 文件加载完成事件
	/// <br>void(byte[][] bytesList)</br>
	/// <br>bytesList:表示加载完成后各个文件的总字节(索引与加载时传递的参数对应)</br>
	/// </summary>
	public event Action<byte[][]> onComplete;
	
	private bool _isDestroyed;
	private FileStream _fileStream;
	private bool _isLoading;
	
	/// <summary>
	/// 异步加载一个或多个本地文件
	/// <br>如果文件不存在将在onComplete(byte[][] bytesList)事件参数bytesList添加一个null</br>
	/// </summary>
	/// <param name="filePaths">可变长度文件路径列表,如: @"C:\Users\Administrator\Desktop\views0.xml"</param>
	public async void loadAsync(params string[] filePaths){
		onLoadStart();

		byte[][] outBytesList=new byte[filePaths.Length][];
		for(int i=0;i<filePaths.Length;i++){
			byte[] buffer=null;
			string filePath=filePaths[i];
			await Task.Run(()=>{
				if(File.Exists(filePath)){
					_fileStream=File.OpenRead(filePath);

					int fileLength=(int)_fileStream.Length;
					buffer=new byte[fileLength];

					_fileStream.Read(buffer,0,fileLength);
				}
			});
			if(_isDestroyed){
				//加载过程中,删除该脚本绑定的对象时,打断
				break;
			}
			outBytesList[i]=buffer;
			dispose();
		}

		//所有加载完成
		if(!_isDestroyed){
			onLoadCompleteAll(outBytesList);
		}
	}

	private void onLoadStart(){
		_isLoading=true;
	}

	private void onLoadCompleteAll(byte[][] outBytesList){
		_isLoading=false;
		onComplete?.Invoke(outBytesList);
	}

	private void dispose(){
		if(_fileStream!=null){
			_fileStream.Dispose();
			_fileStream.Close();
			_fileStream=null;
		}
	}
	
	public void destroy(){
		if(_isDestroyed)return;
		_isDestroyed=true;
		
		dispose();
	}
	
	public bool isLoading{ get => _isLoading; }

}

使用 Resources.Load 加载 xml :
例:加载 Assets/Resources/WorkingMode/PhoneMessages.xml

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <placePoint nameEN="XiAn" nameCN="西安" />
  <placePoint nameEN="NanNing" nameCN="南宁" />
</root>
  • Resources 同步加载 xml:
    using System.Collections;
    using UnityEngine;
    using UnityEngine.UI;
    
    public class ResourcesLoadXml : MonoBehaviour {
    
    	private void LoadXml () {
    		// 此处的 xml 路径为 Resources 文件夹下的子目录,不需要后缀
    		TextAsset xmlAsset = Resources.Load<TextAsset>("WorkingMode/PhoneMessages"); 
    
    		var xmlDoc = new System.Xml.XmlDocument();
    
    		// 添加 xml 声明 <?xml version="1.0" encoding="utf-8" ?>
    		var xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
    		xmlDoc.AppendChild(xmlDeclaration);
    
    		// 使用 字符串创建 xml 文档
    		xmlDoc.LoadXml(xmlAsset.text);
    
    		var rootNode = xmlDoc.SelectSingleNode("root");
    		var placePointNodes = rootNode.SelectNodes("placePoint");
    		for (int i = 0, len = placePointNodes.Count; i < len; i++) {
    			var placePointNode = placePointNodes[i];
    			Debug.Log($"{placePointNode.Attributes["nameEN"].Value}");
    		}
    
    		/*
    		输出:
    		XiAn
    		NanNing
    		*/
    	}
    
    	private void Start () {
    		LoadXml();
    	}
    
    }
    
  • Resources 异步加载 xml:
    using System.Collections;
    using UnityEngine;
    using UnityEngine.UI;
    
    public class ResourcesLoadAsyncXml : MonoBehaviour {
    
    	private IEnumerator LoadXmlAsync () {
    		// 此处的 xml 路径为 Resources 文件夹下的子目录,不需要后缀
    		ResourceRequest resourceRequest = Resources.LoadAsync<TextAsset>("WorkingMode/PhoneMessages");
    		while (!resourceRequest.isDone) {
    			yield return null;
    		}
    		TextAsset xmlAsset = (TextAsset)resourceRequest.asset;
    		var xmlDoc = new System.Xml.XmlDocument();
    
    		// 添加 xml 声明 <?xml version="1.0" encoding="utf-8" ?>
    		var xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
    		xmlDoc.AppendChild(xmlDeclaration);
    
    		// 使用 字符串创建 xml 文档
    		xmlDoc.LoadXml(xmlAsset.text);
    
    		var rootNode = xmlDoc.SelectSingleNode("root");
    		var placePointNodes = rootNode.SelectNodes("placePoint");
    		for (int i = 0, len = placePointNodes.Count; i < len; i++) {
    			var placePointNode = placePointNodes[i];
    			Debug.Log($"{placePointNode.Attributes["nameEN"].Value}");
    		}
    
    		/*
    		输出:
    		XiAn
    		NanNing
    		*/
    	}
    
    	private void Start () {
    		StartCoroutine(nameof(LoadXmlAsync));
    	}
    
    }
    

posted on 2019-09-27 20:24  kingBook  阅读(516)  评论(0编辑  收藏  举报