1

I am trying to import and export to treeview from XML file. But i am having this issue. sample treeview have one root node and two child nodes of same parent. The codes i am using for exporting and importing doesn't work. When I export the treeview the saved XML file is like this:

<?xml version="1.0" encoding="utf-8" ?>
<AAA>
BBBCCC</AAA>

When I import that xml file to treeview it look like this after import xml to treeview . Codes that i am using for export and import are:

//Open the XML file, and start to populate the treeview
private void populateTreeview()
{
    OpenFileDialog dlg = new OpenFileDialog();
    dlg.Title = "Open XML Document";
    dlg.Filter = "XML Files (*.xml)|*.xml";
    dlg.FileName = Application.StartupPath + "\\..\\..\\example.xml";

    if (dlg.ShowDialog() == DialogResult.OK)
    {
        try
        {
            //Just a good practice -- change the cursor to a 
            //wait cursor while the nodes populate
            this.Cursor = Cursors.WaitCursor;
            //First, we'll load the Xml document
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(dlg.FileName);        

            // Now, clear out the treeview, 
            // and add the first (root) node
            treeView1.Nodes.Clear();
            treeView1.Nodes.Add(new TreeNode(xDoc.DocumentElement.Name));

            TreeNode tNode = new TreeNode();
            tNode = (TreeNode)treeView1.Nodes[0];

            // We make a call to addTreeNode, 
            // where we'll add all of our nodes
            addTreeNode(xDoc.DocumentElement, tNode);

            // Expand the treeview to show all nodes
            treeView1.ExpandAll();    
        }
        catch(XmlException xExc) 
        {
            // Exception is thrown is there is an error in the Xml
            MessageBox.Show(xExc.Message);
        }
        catch(Exception ex) //General exception
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            this.Cursor = Cursors.Default; //Change the cursor back
        }
    }
}

// This function is called recursively until all nodes are loaded
private void addTreeNode(XmlNode xmlNode, TreeNode treeNode)
{
    XmlNode xNode;
    TreeNode tNode;
    XmlNodeList xNodeList;

    if (xmlNode.HasChildNodes)    // The current node has children
    {
        xNodeList = xmlNode.ChildNodes;

        for(int x = 0; x <= xNodeList.Count - 1; x++) 
        {
            // Loop through the child nodes
            xNode = xmlNode.ChildNodes[x];
            treeNode.Nodes.Add(new TreeNode(xNode.Name));
            tNode = treeNode.Nodes[x];
            addTreeNode(xNode, tNode);
        }
    }
    else //No children, so add the outer xml (trimming off whitespace)
        treeNode.Text = xmlNode.OuterXml.Trim();
}

private XmlTextWriter xr;

public void exportToXml2(TreeView tv, string filename) 
{
    xr = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
    xr.WriteStartDocument();
    //Write our root node
    xr.WriteStartElement(treeView1.Nodes[0].Text);

    foreach (TreeNode node in tv.Nodes)
    {
        saveNode2(node.Nodes);
    }

    //Close the root node
    xr.WriteEndElement();
    xr.Close();
}

private void saveNode2(TreeNodeCollection tnc)
{
    foreach (TreeNode node in tnc)
    {
        // If we have child nodes, we'll write 
        // a parent node, then iterate over
        // the children
        if (node.Nodes.Count > 0)
        {
            xr.WriteStartElement(node.Text);
            saveNode2(node.Nodes);
            xr.WriteEndElement();    
        } 
        else //No child nodes, so we just write the text
        {
            xr.WriteString(node.Text);
        }
    }
}

Where is the problem?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Please [edit](https://stackoverflow.com/posts/48376642/edit) your question to contain the relevant code as code block, not as a link. – Fildor Jan 22 '18 at 08:01

3 Answers3

0

You are using language other than English . please convert and save .

var text = File.ReadAllText(file, Encoding.GetEncoding(codePage));

how-to-read-text-files-with-ansi-encoding-and-non-english-letters

File.WriteAllText(filepath, filetext, Encoding.Unicode);

or

 new System.IO.StreamWriter(new FileStream(file_name,FileMode.OpenOrCreate),Encoding.ASCII);

read-write-text-file-ansi-utf8-unicode

how-to-convert-utf7-string-into-ansi-in-csharp

Jophy job
  • 1,924
  • 2
  • 20
  • 38
0

The code is fine. The xml should look like this

<?xml version="1.0" encoding="utf-8" ?>
<AAA>
   <BBB/>
   <CCC/>
</AAA>
jdweng
  • 33,250
  • 2
  • 15
  • 20
0

ok, I modified a few lines and I managed what i want to.

Firstly, I add char array for special characters. And use them for trim() function.

 private void addTreeNode(XmlNode xmlNode, TreeNode treeNode)
        {
            **char[] karakter = new char[] { '<', '>', '/' };**
            XmlNode xNode;
            TreeNode tNode;
            XmlNodeList xNodeList;
            if (xmlNode.HasChildNodes) //The current node has children
            {
                xNodeList = xmlNode.ChildNodes;
                for (int x = 0; x <= xNodeList.Count - 1; x++)
                {
                    xNode = xmlNode.ChildNodes[x];
                    treeNode.Nodes.Add(new TreeNode(xNode.Name));
                    tNode = treeNode.Nodes[x];
                    addTreeNode(xNode, tNode);
                }
            }
            else
            {
                treeNode.Text = xmlNode.OuterXml.Trim(**karakter**);
            }

secondly, if there is no child nodes I used WriteRaw method instead of WriteString method.Because special characters are replaced by WriteString method.

private void saveNode2(TreeNodeCollection tnc)
{
    foreach (TreeNode node in tnc)
    {
        if (node.Nodes.Count > 0)
        {
            xr.WriteStartElement(node.Text);
            saveNode2(node.Nodes);
            xr.WriteEndElement();
        }
        else 
        {
            **xr.WriteRaw($"<{node.Text}/>");**
        }
    }

But when I try to save treeview with two roots, It doesn't write the last root. Any opinion? Childs of last root is written as childs of first root. Other then that codes work.