在unity3d中使用xml文件存储游戏的账号和密码,优点:方便查看者查看。
增删改查:代码如下
//这个是打包安卓和pc端的设置路径
// DataPath = Application.persistentDataPath + @"\yangfufeng.xml";
/// <summary>
/// 注册账号和密码
/// </summary>
public void LoginAccountNumberAndPassWord()
{
//注册账号是否重号的判断
bool isExit = false;
//定义路径
string path = Application.dataPath + "/Xml/xml_player.xml";
//如果账号和密码有一个为空,则不能创建。
if (accountNumber.text.Trim().ToString() != "" && passWord.text.Trim().ToString() != "")
{
//判断该路径下的文件是否存在
if (!File.Exists(path))
{
XmlDocument xmlDoc = new XmlDocument();
//根节点创建
XmlElement root = xmlDoc.CreateElement("Sign");
XmlElement player = xmlDoc.CreateElement("player");
player.SetAttribute("name", accountNumber.text);
player.SetAttribute("passWord", passWord.text);
xmlDoc.AppendChild(root);
root.AppendChild(player);
//保存xml文件(保存到的路径)
xmlDoc.Save(path);
}
else
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
XmlNodeList nodelist = xmlDoc.SelectSingleNode("Sign").ChildNodes;
foreach (XmlElement xe in nodelist)
{
if (accountNumber.text.Trim().ToString() == xe.GetAttribute("name"))
{
return;
}
}
if (!isExit)
{
XmlNode root = xmlDoc.SelectSingleNode("Sign");
XmlElement player = xmlDoc.CreateElement("player");
player.SetAttribute("name", accountNumber.text);
player.SetAttribute("passWord", passWord.text);
root.AppendChild(player);
//保存xml文件(保存到的路径)
xmlDoc.Save(path);
}
}
}
}
/// <summary>
/// 知道账号和密码,然后修改账号和密码
/// </summary>
public void AlterAccountNumberAndPassWord()
{
//定义路径
string path = Application.dataPath + "/Xml/xml_player.xml";
//判断要修改的xml文件是否存在
if (File.Exists(path))
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
XmlNodeList nodeList = xmlDoc.SelectSingleNode("Sign").ChildNodes;
foreach (XmlElement item in nodeList)
{
if (item.GetAttribute("name") == AlterAccountNumber.text.Trim().ToString() && item.GetAttribute("passWord") == AlterPassWord.text.Trim().ToString())
{
item.SetAttribute("name", NormalAccountNumber.text.Trim().ToString());
item.SetAttribute("passWord", NormalPassWord.text.Trim().ToString());
}
}
xmlDoc.Save(path);
}
}
/// <summary>
/// 删除账号
/// </summary>
public void DeleteAccountNumber()
{
//定义路径
string path = Application.dataPath + "/Xml/xml_player.xml";
if (File.Exists(path))
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
XmlNodeList nodeList = xmlDoc.SelectSingleNode("Sign").ChildNodes;
foreach (XmlElement item in nodeList)
{
if (item.GetAttribute("name") == AlterAccountNumber.text.Trim().ToString() && item.GetAttribute("passWord") == AlterPassWord.text.Trim().ToString())
{
item.RemoveAll();
}
}
xmlDoc.Save(path);
}
}
关注微信公众号:GameResources 获取游戏资源