有些时候,经常会使用Xml文件来存储一些程序中的内容,下面记录一下在Android端使用Xml的情况。以存储IP为例
注:此方法中的存储的XMl文件,在外部我们是无法看见的,只有使用脚本控制。
首先是保存IP
/// <summary>
/// 保存IP
/// </summary>
/// <param name="iP">要保存的IP地址</param>
public void SaveIp(string iP)
{
//android端的保存路径
string filepath = Application.persistentDataPath + @"/IP.xml";
if (!File.Exists(filepath))
{
XmlDocument xmlDoc = new XmlDocument();
XmlNode docNode = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
//创建root节点,也就是最上一层节点
XmlElement root = xmlDoc.CreateElement("IP");
root.InnerText = iP;
xmlDoc.AppendChild(root);
xmlDoc.Save(filepath);
Debug.Log("createIP OK!");
}
else
{
XmlDocument xmlDoc = new XmlDocument();
XmlNode docNode = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
//根据路径将XML读取出来
xmlDoc.Load(filepath);
XmlNode root = xmlDoc.SelectSingleNode("IP");
root.InnerText = iP;
xmlDoc.Save(filepath);
Debug.Log(iP);
}
}
接下来的是读取Xml中存储的IP
/// <summary>
/// 读取IP
/// </summary>
public void ReadIP()
{
string filepath = Application.persistentDataPath + @"/IP.xml";
if (File.Exists(filepath))
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filepath);
XmlNode root = xmlDoc.SelectSingleNode("IP");
IP = root.InnerText.ToString().Trim();
}
else
{
SaveIp(IP);
}
}