C# 操作XML文件
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace VSTestHelper
{
public class XMLHelper
{
public List<string> registryName = new List<string>();
public List<string> registryValue = new List<string>();
public string lastRegistry;
XmlDocument myXmlDoc = new XmlDocument();
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);
}
public void GenerateXMLFile(string xmlFilePath)
{
try
{
XmlElement rootElement = myXmlDoc.CreateElement("Registry");
myXmlDoc.AppendChild(rootElement);
XmlElement firstLevelElement1 = myXmlDoc.CreateElement("RegistryList");
firstLevelElement1.SetAttribute("Name", "name");
firstLevelElement1.SetAttribute("Value", "value");
rootElement.AppendChild(firstLevelElement1);
myXmlDoc.Save(xmlFilePath);
}
catch (Exception e)
{
Console.WriteLine(e.Message.ToString());
}
}
public bool RegistryFile(string xmlFilePath)
{
bool _exist = false;
if (Directory.Exists(xmlFilePath))
{
Console.WriteLine("The Registry Path has been existed!");
_exist = true;
return _exist;
}
if(_exist==true){
GenerateXMLFile(xmlFilePath);
}
return _exist;
}
public List<string> GetXMLInformation(string xmlFilePath)
{
try
{
myXmlDoc.Load(xmlFilePath);
XmlNode rootNode = myXmlDoc.SelectSingleNode("Registry");
XmlNodeList firstLevelNodeList = rootNode.ChildNodes;
foreach (XmlNode node in firstLevelNodeList)
{
if (node.HasChildNodes)
{
XmlNodeList secondLevelNode1 = node.ChildNodes;
foreach (XmlElement xmlElem in secondLevelNode1)
{
registryName.Add(xmlElem.Name);
registryValue.Add(xmlElem.InnerText);
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message.ToString());
}
return registryName;
}
public string GetLastXMLInformation(string xmlFilePath)
{
try
{
myXmlDoc.Load(xmlFilePath);
XmlNode rootNode = myXmlDoc.SelectSingleNode("Registry");
XmlNodeList firstLevelNodeList = rootNode.ChildNodes;
foreach (XmlNode node in firstLevelNodeList)
{
if (node.HasChildNodes)
{
XmlNode lastNode = node.LastChild;
string lastNodeName = lastNode.Name;
string lastNodeValue = lastNode.InnerText;
lastRegistry = lastNodeName + " = " + lastNodeValue;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message.ToString());
}
return lastRegistry;
}
public void AddXmlInformation(string xmlFilePath, string name, string value)
{
try
{
myXmlDoc.Load(xmlFilePath);
foreach (XmlNode node in myXmlDoc.FirstChild.ChildNodes)
{
XmlElement newElement = myXmlDoc.CreateElement(name);
newElement.InnerText = value;
node.AppendChild(newElement);
}
myXmlDoc.Save(xmlFilePath);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}

浙公网安备 33010602011771号