1.导出xml文件的方法
public void CreateXmlFile()
{
XmlDocument xmlDoc = new XmlDocument();
//创建类型声明节点
XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
xmlDoc.AppendChild(node);
DataTable dt = dal.GetDataBySql("生成XML相关查询语句 ");
//创建根节点
XmlNode root = xmlDoc.CreateElement("users");
xmlDoc.AppendChild(root);
for (int i = 0; i < dt.Rows.Count; i++)
{
CreateNode(xmlDoc, root, dt.Rows[i]);
}
try
{
xmlDoc.Save("d://data2.xml");
MessageBox.Show("导出成功");
}
catch (Exception e)
{
//显示错误信息
MessageBox.Show("导出失败");
}
}
2.生成节点以及节点属性的方法
/// <summary>
/// 创建节点
/// </summary>
/// <param name="xmlDoc"></param>
/// <param name="parentNode"></param>
/// <param name="row"></param>
public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, DataRow row)
{
XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, "user", null);
node.InnerText = row["UserName"].ToString();
CreateAttr((XmlElement)node, "name", row["UserId"].ToString());
CreateAttr((XmlElement)node, "short", row["UserId2"].ToString());
CreateAttr((XmlElement)node, "kqcode", row["employeeNum"].ToString());
CreateAttr((XmlElement)node, "kqname", row["employeeName"].ToString());
parentNode.AppendChild(node);
}
/// <summary>
/// 创建属性
/// </summary>
/// <param name="xmlDoc"></param>
/// <param name="name"></param>
/// <param name="value"></param>
public void CreateAttr(XmlElement xmlDoc, string name, string value)
{
xmlDoc.SetAttribute(name, value);
}