How to save treeview xml in winforms?

fzkim 61 Reputation points
2022-05-16T06:50:28.027+00:00

I'm trying to make a XML Editor(treeview) like 'Microsoft XML notepad'.
so If I edit something in the Editor, it should be reflected in the xmlfile.

-----Example-----

  • before editor
    202167-image.png
  • before xmlfile
    202149-image.png
  • after editor
    202221-image.png
  • after xmlfile
    202212-image.png
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,835 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,278 questions
{count} votes

Accepted answer
  1. Jack J Jun 24,296 Reputation points Microsoft Vendor
    2022-05-16T08:43:09.327+00:00

    @fzkim , Welcome to Microsoft Q&A, please refer to the following code example to save treeview xml in winform.

     public partial class Form1 : Form  
    {  
        public Form1()  
        {  
            InitializeComponent();  
        }  
        public string FileName { get; set; }  
      
        private void button1_Click(object sender, EventArgs e)  
        {  
            OpenFileDialog dlg = new OpenFileDialog();  
            dlg.Title = "Open XML Document";  
            dlg.Filter = "XML Files (*.xml)|*.xml";  
            if (dlg.ShowDialog() == DialogResult.OK)  
            {  
                try  
                {  
                    FileName = dlg.FileName;  
                    this.Cursor = Cursors.WaitCursor;  
                    XmlDocument xDoc = new XmlDocument();  
                    xDoc.Load(dlg.FileName);  
                    treeView1.Nodes.Clear();  
                    treeView1.Nodes.Add(new TreeNode(xDoc.DocumentElement.Name));  
                    TreeNode tNode = new TreeNode();  
                    tNode = (TreeNode)treeView1.Nodes[0];  
                    addTreeNode(xDoc.DocumentElement, tNode);  
                    treeView1.ExpandAll();  
                }  
                catch (Exception ex)  
                {  
                    MessageBox.Show(ex.Message);  
                }  
                finally  
                {  
                    this.Cursor = Cursors.Default;  
                }  
            }  
        }  
      
        private void addTreeNode(XmlNode xmlNode, TreeNode treeNode)  
        {  
            XmlNode xNode;  
            TreeNode tNode;  
            XmlNodeList xNodeList;  
            if (xmlNode.HasChildNodes)  
            {  
                xNodeList = xmlNode.ChildNodes;  
                for (int x = 0; x <= xNodeList.Count - 1; x++)  
                {  
                    xNode = xmlNode.ChildNodes[x];  
                    string nodetext = xNode.Name;  
                    Console.WriteLine(nodetext);  
                    if (!nodetext.Contains("text"))  
                    {  
                        if (xNode.Attributes.Count > 0)  
                        {  
                            for (int i = 0; i < xNode.Attributes.Count; i++)  
                            {  
                                nodetext +=" "+xNode.Attributes[i].Name + "=" + "\"" + xNode.Attributes[i].Value+ "\"";  
                            }  
                        }  
                    }  
      
      
      
                    treeNode.Nodes.Add(new TreeNode(nodetext));  
                    tNode = treeNode.Nodes[x];  
                    addTreeNode(xNode, tNode);  
                }  
            }  
            else  
            {  
                string nodetext = xmlNode.Name + ": ";  
                Console.WriteLine(nodetext);  
                if (!nodetext.Contains("text"))  
                {  
                    if (xmlNode.Attributes.Count > 0)  
                    {  
                        for (int i = 0; i < xmlNode.Attributes.Count; i++)  
                        {  
                            nodetext += xmlNode.Attributes[i].Name + "=" + xmlNode.Attributes[i].Value;  
                        }  
                    }  
                }  
                else  
                {  
                    nodetext = xmlNode.InnerText;  
                }  
                treeNode.Text = nodetext;  
            }  
      
        }  
      
        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)  
        {  
            treeView1.LabelEdit = true;  
            treeView1.SelectedNode.BeginEdit();  
        }  
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)  
        {  
            if (keyData == (Keys.Control | Keys.S))  
            {  
                exportToXml(treeView1, FileName);  
      
                return true;  
            }  
            return base.ProcessCmdKey(ref msg, keyData);  
        }  
        //保存  
        StreamWriter sr = null;  
        public void exportToXml(TreeView tv, string filename)  
        {  
            sr = new StreamWriter(filename, false, System.Text.Encoding.UTF8);  
            sr.WriteLine("<" + tv.Nodes[0].Text + ">");  
        
            foreach (TreeNode node in tv.Nodes)  
            {  
             
                saveNode(node.Nodes);  
            }  
            //Close the root node  
            sr.WriteLine("</" + tv.Nodes[0].Text + ">");  
       
            sr.Close();  
            var lines = File.ReadAllLines(filename).Where(line => !String.IsNullOrWhiteSpace(line));  
            File.WriteAllLines(filename, lines);  
      
        }  
        private void saveNode(TreeNodeCollection tnc)  
        {  
            foreach (TreeNode node in tnc)  
            {  
      
                if (node.Nodes.Count > 0)  
                {  
                    if(node.Text.Contains("="))  
                    {  
                        sr.Write("<" + node.Text + ">");  
                        saveNode(node.Nodes);  
                        sr.WriteLine("</" + node.Text.Split(' ')[0] + ">");  
                    }  
                    else  
                    {  
                        sr.WriteLine("");  
                        sr.Write("<" + node.Text + ">");  
                        saveNode(node.Nodes);  
                        sr.WriteLine("</" + node.Text + ">");  
                    }  
                   
                }  
                else  
                    sr.Write(node.Text);  
            }  
        }  
      
    }  
    

    Tested result:

    202600-3.gif

    Note: After you editing the node, you could press ctrl+s to save it to xml file.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful