(在草稿中保存了一年,,,,不舍得删,还是放出来吧)
XML解析
初学XML,代码仅供参考。主要用于游戏的注册登陆界面
包括XML创建,添加节点及属性内容,查找节点及属性内容
Path:为XML存储路径
BaseNode:为基层结点
主要代码:element.SetAttribute(NodeName, NodeId);SetAttribute添加信息(名称和值)
element.InnerText= "ddddd"; 获取或设置或更改串联内容<>ddddd<>
AppendChild 设置子集关系
xml.Save(path); 一定要保存
XmlReader reader = XmlReader.Create(path);
xml.Load(reader);
查看信息时,开启数据流,查找结束记着关闭 reader.Close();
创建XML文件
public string CreateXML(string path,string BaseNode,string ElementNode,string NodeName,string NodeId)
{
if (!File.Exists(path))
{
//创建XML文件
XmlDocument xml = new XmlDocument();
//创建第一层的节点。
XmlElement root = xml.CreateElement(BaseNode);
//创建第二层的节点。
XmlElement element = xml.CreateElement(ElementNode);
//设置(添加)第二层节点的属性(NodeName为节点名字,NodeId为节点值)
//<User name=”123”/>
element.SetAttribute(NodeName,NodeId);
//如果为结点添加内容<User name=”123”>ddddd</User>
element.InnerText = "ddddd";
root.AppendChild(element);//一层一层的保存
xml.AppendChild(root);
//最后保存文件
xml.Save(path);
return "创建成功";
}
return "已经创建";
}
查找XML信息(判断信息是否正确)
public string LoadXml(string path,string BaseNode, string NodeName,string NodeId, string nodeName,string nodeId)
{
if (File.Exists(path))
{
//创建xml文档
XmlDocument xml = new XmlDocument();
XmlReader reader =XmlReader.Create(path);
xml.Load(reader);
//得到objects节点下的所有子节点
XmlNodeList xmlNodeList =xml.SelectSingleNode(BaseNode).ChildNodes;
//遍历所有子节点
foreach (XmlElement xl1in xmlNodeList)
{
if (xl1.GetAttribute(NodeName) == NodeId)
{
if (xl1.GetAttribute(nodeName) == nodeId)
{
//关闭数据流
return "查找成功";
}
}
}
reader.Close();
return "查找错误";
}
return "文件不存在";
}
添加XML信息
public staticstring addQuality(string path,string BaseNode, string NodeName,string NodeId,string nodeName, string nodeId)
{
if (File.Exists(path))
{
XmlDocument xml = new XmlDocument();
xml.Load(path);
XmlNode root = xml.SelectSingleNode(BaseNode);
XmlNodeList xmlNodeList =xml.SelectSingleNode(BaseNode).ChildNodes;
//遍历所有子节点
foreach (XmlElement xl1in xmlNodeList)
{
if (xl1.GetAttribute(NodeName) == NodeId)
{
if (xl1.HasAttribute(nodeName))
{
return "已经添加";
}
xl1.SetAttribute(nodeName,nodeId);
//最后保存文件
xml.Save(path);
return "添加成功";
}
}
}
return "文件不存在";
}
更改XML信息
public string updateXML(string path,string BaseNode, string NodeName,string NodeId, string nodeName,string nodeId)
{
if (File.Exists(path))
{
XmlDocument xml = new XmlDocument();
xml.Load(path);
XmlNodeList xmlNodeList =xml.SelectSingleNode(BaseNode).ChildNodes;
foreach (XmlElement xl1in xmlNodeList)
{
if (xl1.GetAttribute(NodeName) == NodeId)
{
if (xl1.HasAttribute(nodeName))
{
xl1.SetAttribute(nodeName, nodeId);
xml.Save(path);
return "更改成功";
}
}
return "未找到";
}
}
return "文件不存在";
}