一、 生成XML文件
1. 手动编写XML文件
private void SaveXml(XmlTextWriter writer)
{
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("Root", "http://tempuri.org/Root.xsd");
foreach (var item in models)
{
writer.WriteStartElement("Frames");
writer.WriteElementString("FrameId", item.Id.ToString());
writer.WriteElementString("TimeStamp", item.TimeStamp);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.Close();
}
private void Save(object sender)
{
System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
saveFileDialog.Filter = "XML Files|*.xml";
saveFileDialog.Title = "Save a XML File";
if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
XmlTextWriter writer = new XmlTextWriter(saveFileDialog.FileName, System.Text.Encoding.UTF8);
SaveXmlLog(writer);
}
}
2. DataTable转XML
public static void ConvertDatatableToXML(DataTable dataTable,string xmlPath,string xmlFileName,int titleLine=0)
{
using (System.IO.StringWriter stream = new System.IO.StringWriter())
{
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(stream))
{
dataTable.WriteXml(xmlTextWriter);
File.WriteAllText(xmlPath + xmlFileName, stream.ToString(),Encoding.UTF8);
stream.Close();
xmlTextWriter.Close();
}
}
}
二、打开XML文件
private void LoadXMLFile()
{
System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
openFileDialog.Filter = "XML Files|*.xml";
openFileDialog.Title = "Select a XML File";
openFileDialog.CheckFileExists = true;
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(openFileDialog.FileName);
XmlNodeList lisFrameNum = xmlDoc.GetElementsByTagName("Frames");
}
}
}