C#写XML
下段代码将会生成形如:
这样的XML文件。下段代码中有很多是自定义的字符串常量。还有使用Hashtable的地方。
public void Save()
{
FileInfo fi = new FileInfo(_fileName);
if (!fi.Exists)// to do
fi.Create();
XmlTextWriter xw = null;
try
{
XmlDocument xml = new XmlDocument();
xw = new XmlTextWriter(_fileName, Encoding.UTF8);
xml.WriteTo(xw);
System.Collections.ICollection keys = _ht.Keys;
xw.WriteStartElement(“Root”);
foreach(string key in keys)
{
xw.WriteStartElement(“Node”);
xw.WriteAttributeString(KEY, key);
xw.WriteAttributeString(VALUE, _ht[key] as string);
xw.WriteEndElement();
}
xw.WriteEndElement();
xml.Save(xw);
}
catch (UnauthorizedAccessException)
{
// to do
//access deny
}
catch (Exception)
{
//to do
}
finally
{
if (null != xw)
{
xw.Close();
}
}
}