0

我试图保存和加载我的树视图的树节点,我用树节点列表创建了树,如下所示:

  [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文件我不知道在那里写什么我应该怎么做才能使它工作?它有无效操作异常错误

4

1 回答 1

1

这是一种更简单的方法,下面的代码更多地用于将任何对象转换为 XML 一旦您理解了这一点,请随时在需要的时间和地点尝试高级代码 如何将树视图转换为 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);
}
于 2012-08-20T08:09:36.443 回答