C# 替换ini文件的xml类
我正在学习C#.NET 2008中的Windows窗体,我想构建一个类来处理简单的xml文件(像INI文件一样的配置文件),但我只需要一个简单的类(open、getvalue、setvalue、creategroup、save和close函数)来代替INI文件 我已经做了一些工作,但当我需要创建不同的组时,我遇到了困难,比如:C# 替换ini文件的xml类,c#,.net,xml,linq,linq-to-xml,C#,.net,Xml,Linq,Linq To Xml,我正在学习C#.NET 2008中的Windows窗体,我想构建一个类来处理简单的xml文件(像INI文件一样的配置文件),但我只需要一个简单的类(open、getvalue、setvalue、creategroup、save和close函数)来代替INI文件 我已经做了一些工作,但当我需要创建不同的组时,我遇到了困难,比如: <?xml version="1.0" encoding="utf-8"?> <CONFIG> <General> <
<?xml version="1.0" encoding="utf-8"?>
<CONFIG>
<General>
<Field1>192.168.0.2</Field1>
</General>
<Data>
<Field1>Joseph</Field1>
<Field2>Locked</Field2>
</Data>
</CONFIG>
要保存文档,请执行以下操作:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(FilePath);
xmlDoc.Save(FilePath);
要获得价值:
public string getValue(string Field)
{
string result = "";
try
{
XmlNodeList xmlComum = xmlDoc.GetElementsByTagName(Field);
if (xmlComum.Item(0) == null)
result = "";
else
result = xmlComum.Item(0).InnerText;
}
catch (Exception ex)
{
return "";
}
return result;
}
要设置值,请执行以下操作:
public void setValue(string Group, string Field, string FieldValue)
{
try
{
XmlNodeList xmlComum = xmlDoc.GetElementsByTagName(Field);
if (xmlComum.Item(0) == null)
{
xmlComum = xmlDoc.GetElementsByTagName(Group);
if (xmlComum.Item(0) == null)
{
// create group
createGroup(Group);
xmlComum = xmlDoc.GetElementsByTagName(Group);
}
XmlElement xmlE = xmlDoc.CreateElement(Field);
XmlText xmlT = xmlDoc.CreateTextNode(FieldValue);
xmlE.AppendChild(xmlT);
xmlComum.Item(0).AppendChild(xmlE);
}
else
{
// item already exists, just change its value
xmlComum.Item(0).InnerText = Value;
}
xmlDoc.Save(FilePath);
}
catch (Exception ex)
{
}
}
CreateGroup代码:
public void createGroup(string Group)
{
try
{
XmlElement xmlComum = xmlDoc.CreateElement(Group);
xmlDoc.DocumentElement.AppendChild(xmlComum);
xmlDoc.Save(FilePath);
}
catch (Exception ex)
{
}
}
尽管您可能在项目中“使用”System.Linq,但您并没有使用所谓的“Linq到XML”类。这使得事情变得简单了5倍,即使你没有在他们身上使用LINQ!使用System.Linq.XML名称空间访问这些新的XML类(XDocument、XElement等)
- 良好的DNR电视视频播放/和
- A一般,特别是Linq到XML
System.configuration
就是您的朋友,因为它处理对App.Config
的读写,这是一个专门为此设计的XML文件
以下是一些细节和示例:
当然,如果要编写XML文件的通用接口,
System.Linq.XML
是正确的选择。首先,您没有使用System.Linq,而是使用旧的XmlDocument类。第二,摆脱那些try/catch块,你只是在吃可能会告诉你做错了什么的异常。你是对的,Linq更容易,你救了我的命!谢谢大家!!
XDocument XDoc = XDocument.Load("ThePath")
String Field1 = (String)XDoc.Root.Element("Data").Element("Field1")