/// <summary>
/// 修改节点
/// </summary>
/// <param name="user">UserSafe 实体类</param>
/// <returns></returns>
public XmlDocument UpdateUserNode(UserSafe user)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(fileUserName);//加载xml文件,路径未指定时默认在当前项目环境下
XmlNodeList nodelist = xmlDoc.SelectSingleNode("item").ChildNodes;
foreach (XmlNode node in nodelist)
{
XmlElement xe = (XmlElement)node;
if (xe.ParentNode.FirstChild.Name == "Safe")//找到相应节点
{
XmlNodeList childNodeList = xe.ChildNodes;//继续获取子节点的所有子节点
foreach (XmlNode xn2 in childNodeList)//遍历子节点的所有子节点
{
XmlElement xmlDoc3 = (XmlElement)xn2;//转换类型
if (xmlDoc3.Name == "username")//找到相应节点
{
if (xmlDoc3.InnerText == user.USERNAME)
{
xmlDoc3.InnerText = user.USERNAME;//修改相应节点的值
}
break;
}
if (xmlDoc3.Name == "insertdate")//找到相应节点
{
if (xmlDoc3.InnerText != user.INSERTDATE)
{
xmlDoc3.InnerText = user.INSERTDATE;//修改相应节点的值
}
break;
}
xmlDoc.AppendChild(xn2);
}
break;
}
}
xmlDoc.Save(fileUserName);//保存
return xmlDoc;
}
/// <summary>
/// 创建节点
/// </summary>
/// <param name="user">UserSafe 实体类</param>
/// <param name="fileName">文件名</param>
/// <returns></returns>
private XmlDocument CreateUserFileMethod(UserSafe user, string fileName)
{
XmlDocument xmlDoc = new XmlDocument();
//创建类型声明节点
XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
xmlDoc.AppendChild(node);
//创建根节点
XmlNode root = xmlDoc.CreateElement("item");
xmlDoc.AppendChild(root);
XmlNode node1 = xmlDoc.CreateNode(XmlNodeType.Element, "Safe", null);
CreateNode(xmlDoc, node1, "insertdate", user.INSERTDATE);
CreateNode(xmlDoc, node1, "username", user.USERNAME);
root.AppendChild(node1);
XmlAttribute genre = (XmlAttribute)xmlDoc.CreateAttribute("genre");
genre.InnerText = user.USERNAME;
node1.Attributes.Append(genre);
try
{
xmlDoc.Save(fileName);
}
catch (Exception e)
{
//显示错误信息
Console.WriteLine(e.Message);
}
return xmlDoc;
}
public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
{
XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
node.InnerText = value;
parentNode.AppendChild(node);
}