unity C# xml创建,获取,修改,删除(android同样适用)

闲话不说,代码附上:
先看xml文件:

<?xml version="1.0" encoding="utf-8"?>
<Player>
  <Player00>
    <Postion name="Postion">
      <X>-9.726</X>
      <Y>0.791</Y>
      <Z>8.063321</Z>
    </Postion>
    <Level>1</Level>
    <Exp>0</Exp>
    <Hp>5</Hp>
  </Player00>
</Player>

C#脚本

using UnityEngine;
using System.Xml;
using System.Collections.Generic;
using System.IO;
using System;

public class LoadPlayerInfo : MonoBehaviour {
    public static LoadPlayerInfo _loadplayerinfo;

    //xml信息
    public string xmlName = "PlayerInfo";//xml文件名
    public string rootNodeName = "Player";//根节点name

    //申明xml对象
    private static XmlDocument xmlDoc = new XmlDocument();
    //申明src
    private static string Path;
    void Awake()
    {
        _loadplayerinfo = this;
        CreatePath();
    }

    /// <summary>
    /// 创建xml文件,
    /// </summary>
    public void CreatePath()
    {
        Path = Application.persistentDataPath + "/"+xmlName+".xml";
        if (!File.Exists(Path))
        {
            xmlDoc.LoadXml(((TextAsset)Resources.Load("Xml/"+xmlName)).text);
            xmlDoc.Save(Path);//存储xml文件
            Debug.Log("Create Success:"+ Path);
        }
        else
        {
            xmlDoc.Load(Path);
            Debug.Log("Use Success:"+Path);
        }
    }

    void Start()
    {
        //Dictionary<string, string> dic = new Dictionary<string, string>();
        //dic.Add("X", "66");
        //dic.Add("Y", "44");
        //dic.Add("Z", "20");
        //ChangeValue(1, "Postion", dic);
        //Debug.Log(CreatePlayerNode(2));
        //Debug.Log(GetValue(1, "Level")["Level"]);
        //SaveValue(1, "Level", dic);
        //Debug.Log(SelectAllNode("Level").Count);
        //Debug.Log(DeteleNodes(2));

    }

    /// <summary>
    /// 获取数据
    /// </summary>
    /// <param name="playerId">为player的唯一编号</param>
    /// <param name="nodeName">获取的标签的name</param>
    /// <returns>返回获取标签的childnode的innertext和name,如果没有返回null</returns>
    public  Dictionary<string ,string> GetValue(int playerId,string nodeName)
    {
        //没有玩家信息就新建
        if (CanCreateNode(playerId))
        {
            CreatePlayerNode(playerId);
        }
        XmlNodeList xmlRoottList = xmlDoc.SelectSingleNode(rootNodeName).ChildNodes;
        string playerName = rootNodeName + "0" + playerId;
        foreach (XmlElement x3 in xmlRoottList)
        {
            if (x3.Name.Equals(playerName))
            {
                Dictionary<string, string> dictionary = new Dictionary<string, string>();
                foreach (XmlElement x1 in x3)
                {
                    if (x1.Name.Equals(nodeName))
                    {
                        if (x1.HasAttribute("name"))
                        {
                            foreach (XmlElement x2 in x1)
                            {
                                dictionary.Add(x2.Name, x2.InnerText);
                                Debug.Log(x2.Name + ":Get");
                            }
                        }
                        else
                        {
                            dictionary.Add(x1.Name, x1.InnerText);
                        }
                        Debug.Log("Get Success");
                        return dictionary;
                    }
                }
            }
        } 
        return null;
    }

    /// <summary>
    /// 修改数据
    /// </summary>
    /// <param name="playerId">player唯一id</param>
    /// <param name="nodeName">需要修改的标签name</param>
    /// <param name="dictionary">输入修改的值,如果标签无子标签,则字典的key为标签的名字,否则为子标签的名字</param>
    /// <returns>返回是否修改成功</returns>
    public  bool ChangeValue(int playerId, string nodeName, Dictionary<string, string> dictionary)//存储数据
    {
        //如果没有玩家创建一个新的玩家
        if (CanCreateNode(playerId))
        {
            Debug.Log("None");
            CreatePlayerNode(playerId);
        }
        string playerName = rootNodeName + "0" + playerId;
        XmlNodeList nodeRootList = xmlDoc.SelectSingleNode(rootNodeName).ChildNodes;
        foreach(XmlElement x3 in nodeRootList)
        {
            if (x3.Name.Equals(playerName))
            {
                foreach (XmlElement x1 in x3)
                {
                    if (x1.Name.Equals(nodeName))
                    {
                        if (dictionary.Count == 1)
                        {
                            x1.InnerText = dictionary[nodeName];
                        }
                        else if (dictionary.Count > 1)
                        {
                            foreach (XmlElement x2 in x1)
                            {
                                if (dictionary.ContainsKey(x2.Name))
                                {
                                    x2.InnerText = dictionary[x2.Name];
                                }
                            }
                        }
                    }
                }
            }
        }

        try
        {
            xmlDoc.Save(Path);
            Debug.Log("Change Success");
            return true;
        }
        catch(Exception e)
        {
            Debug.Log("Change Error:"+e.Message);
            return false;
        }

    }

    /// <summary>
    /// 创建一个新的player
    /// </summary>
    /// <param name="playerId">新player的唯一id</param>
    /// <returns>返回是否创建成功(0.创建成功 1.创建失败 2.已经有重复的对象)</returns>
    public  int CreatePlayerNode(int playerId)
    {
        if (CanCreateNode(playerId))
        {
            //最上层节点
            XmlNode root = xmlDoc.SelectSingleNode(rootNodeName);//创寻找根节点
            XmlElement newPlayerNode = xmlDoc.CreateElement(rootNodeName + "0" + playerId);
            //遍历第一层子节点所有name
            List<string> rootList = SelectAllNode("root");
            //第一层子节点
            XmlElement childInRoot;
            //接收值得dictionary
            Dictionary<string, string> tempDic = new Dictionary<string, string>();
            for (int i = 0; i < rootList.Count; i++)
            {
                //创建第一层子节点
                childInRoot = xmlDoc.CreateElement(rootList[i]);
                //遍历第二层子节点所有节点名
                List<string> childList = SelectAllNode(rootList[i]);

                //Debug.Log(rootList[i]);
                if (childList.Count == 0)//如果没有子节点,输入默认值
                {
                    tempDic = GetValue(0, rootList[i]);
                    childInRoot.InnerText = tempDic[rootList[i]];
                    tempDic.Clear();
                }
                else//如果有子节点则再次遍历
                {
                    XmlElement child00;
                    childInRoot.SetAttribute("name", childInRoot.Name);//设置name
                    tempDic = GetValue(0, rootList[i]);
                    for (int j = 0; j < childList.Count; j++)
                    {
                        child00 = xmlDoc.CreateElement(childList[j]);
                        child00.InnerText =tempDic[childList[j]];//输入默认值
                        childInRoot.AppendChild(child00);
                    }
                    tempDic.Clear();
                }
                newPlayerNode.AppendChild(childInRoot);
                root.AppendChild(newPlayerNode);
            }

            //存储
            try
            {
                xmlDoc.Save(Path);
                Debug.Log("Create Node Success:" + rootNodeName + "0" + playerId);
                return 0;
            }
            catch (Exception e)
            {
                Debug.Log("Create Error:"+e.Message);
                return 1;
            }
        }
        else
        {
            return 2;
        }

    }

    /// <summary>
    /// 查询子目录下所有节点的名字
    /// </summary>
    /// <param name="nodeName">父节点名字</param>
    /// <returns>返回所有节点的名字</returns>
    public  List<string> SelectAllNode(string nodeName)
    {
        List<string> nodeList = new List<string>();
        XmlNodeList xmlList = xmlDoc.SelectSingleNode(rootNodeName).ChildNodes;//获取该层上的所有子节点
        foreach(XmlElement x3 in xmlList)
        {
            if (x3.Name.Equals(rootNodeName + "00"))
            {
                if (nodeName.Equals("root"))//返回最上层的的所有子节点
                {
                   foreach (XmlElement x1 in x3)
                   {
                        nodeList.Add(x1.Name);
                        //Debug.Log(x1.Name);
                   }
                    return nodeList;
                }
                else//返回第二次的所有子节点
                {
                    //Debug.Log(x3.Name);
                    foreach (XmlElement x1 in x3)
                    {
                        if (x1.Name.Equals(nodeName))
                        {

                            if (x1.HasAttributes)
                            {
                                foreach (XmlElement x2 in x1)
                                {
                                    nodeList.Add(x2.Name);
                                }
                            }
                        }
                    }
                    return nodeList;
                }
           }

          }
        return null;
     }

    /// <summary>
    /// 删除player节点
    /// </summary>
    /// <param name="playerId">player唯一id</param>
    /// <returns>返回删除结果(0,删除成功,2.无节点)</returns>
    public int DeteleNodes(int  playerId)
    {
        XmlNodeList rootList = xmlDoc.SelectSingleNode(rootNodeName).ChildNodes;
        XmlElement root = xmlDoc.DocumentElement;
        foreach(XmlElement x1 in rootList)
        {
            if (x1.Name.Equals(rootNodeName + "0" + playerId))
            {
                root.RemoveChild(x1);
                xmlDoc.Save(Path);
                Debug.Log("Detele Node Success");
                return 0;
            }
        }
        Debug.Log("Has Not Node");
        return 2;
    }

    /// <summary>
    /// 判断是否有重复的player
    /// </summary>
    /// <param name="playerId">所需要判断的playerId</param>
    /// <returns>返回是否有重复的</returns>
    public bool CanCreateNode(int playerId)
    {
        XmlNodeList playerNodeList = xmlDoc.SelectSingleNode(rootNodeName).ChildNodes;
        foreach(XmlElement x1 in playerNodeList)
        {
            if (x1.Name.Equals(rootNodeName + "0" + playerId))
            {
                return false;
            }
        }
        Debug.Log("Has Same Node Name");
        return true;
    }
}

现在可以使用了
注意:playerinfo.xml文件需要放在Resources/Xml文件夹下,Resources/Xml只是为了在本地创建xml文件,运行第一次之后就可以删掉,android平台同样适用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值