xml操作

/// <summary>
/// load xml文件
/// </summary>
/// <returns></returns>
private XmlElement LoadXmlConfig()
{
XmlDocument xml = new XmlDocument();
xml.LoadXml(LoadFileContent());
return xml.DocumentElement;
}

/// <summary>
/// 加载某一文本文件内容 将统计信息暂时保存在临时文件中 该文件内容要在一天统计完后添加到数据库中
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public string LoadFileContent()
{
string fileContent = null;
//判断文件是否存在
if (!File.Exists(path))
{
WriteToConfig("<configuration></configuration>");
}
fileContent = File.ReadAllText(path);
return fileContent;
}

public void WriteToConfig(string content)
{
try
{
using (StreamWriter sw = new StreamWriter(path))
{
sw.Write(content);
}
}
catch (Exception e)
{
throw;
}
}

public void InsertParentNode(string nodeName, string count)
{
XmlElement root = this.LoadXmlConfig();
XmlElement xmlElement = root.OwnerDocument.CreateElement(nodeName);
xmlElement.SetAttribute("value", count);
root.AppendChild(xmlElement);
WriteToConfig(root.OuterXml);
}

public void InsertChildNode(string datelenth, string count, string parentName)
{
XmlElement root = this.LoadXmlConfig();
XmlNode webNode = root.SelectSingleNode(parentName);
if (webNode != null)
{
XmlElement xmlElement = webNode.OwnerDocument.CreateElement(datelenth);
xmlElement.SetAttribute("value", count);
webNode.AppendChild(xmlElement);
WriteToConfig(root.OuterXml);
}
}

原文地址:https://www.cnblogs.com/GreenGrass/p/2681981.html