主要为替代INI的读写,此示例为保存datagridview的columns的部分设置
XML文件格式为:
<?xml version="1.0" encoding="utf-8"?>
<Columns>
<Columns0 Index="0" Visiable="False" HeadText="ID" Width="100" />
<Columns1 Index="1" Visiable="True" HeadText="年份" Width="100" />
<Columns2 Index="2" Visiable="True" HeadText="类型" Width="100" />
<Columns3 Index="3" Visiable="True" HeadText="编号" Width="100" />
</Columns>
读写示例代码如下:
/// <summary>
/// 读XML
/// </summary>
public void RXml()
{
if (File.Exists(Sys_Xml))
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(Sys_Xml);
XmlNode xn= xdoc.SelectSingleNode("Columns");
XmlNodeList xnl = xn.ChildNodes;
foreach (XmlNode xnd in xnl)
{
int idx;
int.TryParse(xnd.Attributes["Index"].Value,out idx);
if (idx <= dataGridView1.Columns.Count)
{
bool vis;
bool.TryParse(xnd.Attributes["Visiable"].Value,out vis);
dataGridView1.Columns[idx].Visible = vis;
dataGridView1.Columns[idx].HeaderText = xnd.Attributes["HeadText"].Value;
int wid;
int.TryParse(xnd.Attributes["Width"].Value,out wid);
dataGridView1.Columns[idx].Width=wid;
}
}
}
}
/// <summary>
/// 写XML
/// </summary>
public void WXml()
{
XmlDocument xdoc = new XmlDocument();
//创建类型声明节点
XmlNode node = xdoc.CreateXmlDeclaration("1.0", "utf-8", "");
xdoc.AppendChild(node);
//创建根节点
XmlNode root = xdoc.CreateElement("Columns");
xdoc.AppendChild(root);
foreach (DataGridViewColumn dc in dataGridView1.Columns)
{
XmlElement xnode = xdoc.CreateElement("Columns" + dc.Index.ToString());
xnode.SetAttribute("Index", dc.Index.ToString());
xnode.SetAttribute("Visiable", dc.Visible.ToString());
xnode.SetAttribute("HeadText", dc.HeaderText);
xnode.SetAttribute("Width", dc.Width.ToString());
root.AppendChild(xnode);
}
xdoc.Save(Sys_Xml);
}