我试图保存并加载我的树视图的treenodes,我创建了一个包含treenodes列表的树,如下所示:
[Serializable]
public class Tree : List<TreeNode>
{
public void Save()
{
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(Tree));
System.IO.FileStream s = new System.IO.FileStream(Application.StartupPath + "\\nodes.xml", System.IO.FileMode.Create);
x.Serialize(s, this);
s.Flush();
s.Close();
}
public static Tree Load()
{
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(Tree));
System.IO.FileStream s = new System.IO.FileStream(Application.StartupPath + "\\nodes.xml", System.IO.FileMode.OpenOrCreate);
Tree tree = x.Deserialize(s) as Tree;
s.Close();
return tree;
}
}
然后在保存按钮中我写了这个:
private void SaveButton_Click(object sender, EventArgs e)
{
this.SaveButton.Enabled = false;
Tree tree = new Tree();
foreach (TreeNode treeNode in this.treeView1.Nodes)
{
tree.Add(treeNode);
}
tree.Save();
MessageBox.Show("Saved Successfully.", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.SaveButton.Enabled = true;
}
在加载的表格中我使用了这个:
private void Form1_Load(object sender, EventArgs e)
{
Tree tree = Tree.Load();
//Process Tree
foreach (TreeNode node in tree)
{
TreeNode treeNode=new TreeNode(node.Text);
this.treeView1.Nodes.Add(node);
}
//End Process Tree
我没有做任何进一步的事情,我认为nodes.xml不正确我不知道在那里写什么如果我想创建xml文件我该怎么做才能使它工作? 它有 invalidopeartionexception错误
答案 0 :(得分:1)
这是一种更简单的方法,下面的代码更多的是将任何对象转换为XML 一旦你理解了这一点,你可以随时随地尝试高级代码 How to convert treeview to xml?
以下是一个如何将序列化和对象转换为XML并对其进行反序列化的示例我希望此示例有所帮助..
**要将任何对象或某些集合写入xml对象,必须具有默认构造函数。
public static string SerializeToXmlString(object objectToSerialize)
{
MemoryStream memoryStream = new MemoryStream();
System.Xml.Serialization.XmlSerializer xmlSerializer =
new System.Xml.Serialization.XmlSerializer(objectToSerialize.GetType());
xmlSerializer.Serialize(memoryStream, objectToSerialize);
ASCIIEncoding ascii = new ASCIIEncoding();
return ascii.GetString(memoryStream.ToArray());
}
**这应该将xml变回一个对象
public static object DeSerializeFromXmlString(System.Type typeToDeserialize, string xmlString)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(xmlString);
MemoryStream memoryStream = new MemoryStream(bytes);
System.Xml.Serialization.XmlSerializer xmlSerializer =
new System.Xml.Serialization.XmlSerializer(typeToDeserialize);
return xmlSerializer.Deserialize(memoryStream);
}