写 XML 文件的
//public static void SetXmlFileValue(string xmlPath, string AppKey, string AppValue)//写xmlPath是文件路径+文件名,AppKey是 Key Name,AppValue是Value
public static void SetXmlFileValue(string xmlPath, string AppKey, string AppValue)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(xmlPath);
XmlNode xNode;
XmlElement xElem1;
XmlElement xElem2;
xNode = xDoc.SelectSingleNode("//appSettings";
xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']";
if (xElem1 != null)
{
xElem1.SetAttribute("value", AppValue);
}
else
{
xElem2 = xDoc.CreateElement("add";
xElem2.SetAttribute("key", AppKey);
xElem2.SetAttribute("value", AppValue);
xNode.AppendChild(xElem2);
}
xDoc.Save(xmlPath);
}
读取 XML 文件节点内容
//public static void GetXmlFileValue(string xmlPath, string AppKey, ref string AppValue)//读xmlPath是文件路径+文件名,AppKey是 Key Name,AppValue是Value
public static string GetXmlFileValue(string xmlPath, string AppKey)
{
string strValue = "";
XmlDocument xDoc = new XmlDocument();
xDoc.Load(xmlPath);
XmlNode xNode;
XmlElement xElem1;
xNode = xDoc.SelectSingleNode("//appSettings";
xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']";
if (xElem1 != null)
{
strValue = xElem1.GetAttribute("value";
}
else
{
// MessageBox.Show ("There is not any information!";
}
return strValue;
}
<?xml version="1.0" encoding="utf-8"?>
<System.Config>
<appSettings>
<add key="Server" value="D085D536F765EEB74123E527CEC0F564" />
<add key="DataBase" value="9323125653A3D08C2C1BF16192A2A2B8" />
<add key="User" value="7DDB8369CD879AE4" />
<add key="Password" value="B46F3E9E2A88B035" />
<!--Export to Excel,Chinese will become wrong code format at utf-8-->
<add key="ExportExcelEncoding" value="gb2312" />
</appSettings>
</System.Config>
读取:GetXmlFileValue(strXmlPath, "Server");
写入:SetXmlFileValue("setup.xml", "Server", "value");
{
if (opFileDlg .ShowDialog() == DialogResult.OK)
{
if(opFileDlg .OpenFile()!=null)
{
twoXML .ReadXml (@opFileDlg .FileName );
foreach (DataRow twoRow in twoXML .Tables ["user"].Rows)
{
DataRow newRow = dsXML.Tables["user"].NewRow();
newRow ["序号"] = twoRow ["序号"];
newRow["标题"] = twoRow["标题"];
newRow["网址"] = twoRow["网址"];
newRow["用户名"] = twoRow["用户名"];
newRow["密码"] = twoRow["密码"];
newRow["时间"] = twoRow["时间"];
newRow["备注"] = twoRow["备注"];
dsXML .Tables ["user"].Rows .Add(newRow);
}
int n = dsXML .Tables ["user"].Rows .Count ;
for(int i=0;i<n;i++)
{
dsXML .Tables ["user"].Rows [i]["序号"]=i+1;
}
dsXML.WriteXml(@"user.xml");
this.Visible = true;
MessageBox.Show("数据导入成功!", "成功"); 中国网管联盟www、bitsCN、com
}
}
else
{
this.Visible = true;
}
}