I have a problem with saving my data from TreeView
. I've googled a lot of topics how to save data from TreeView
to XML
, and I saw i few methods how to make that. But all of them were using WindowsForms application
, and nobody - WPF
. I tried to convert those examples to WPF
, but no one from them do not work correct. Is there any way to make it? One of the ways I tried to port:
void SaveToXml(TreeView tw)
{
XmlDocument d = new XmlDocument();
XmlNode n = d.CreateNode(XmlNodeType.Element, "root", "");
foreach (TreeViewItem t in tw.Items)
{
n.AppendChild(getXmlNode(t, d));
}
d.AppendChild(n);
d.Save(AppDomain.CurrentDomain.BaseDirectory + "out.xml");
}
private XmlNode getXmlNode(TreeViewItem tnode, XmlDocument d)
{
XmlNode n = d.CreateNode(XmlNodeType.Element, tnode.Name, " ");
foreach (TreeViewItem t in tnode.Items)
{
n.AppendChild(getXmlNode(t, d));
}
return n;
}
It throws ArgumentException
"Local element's and attribute's names cannot be empty". I'm trying to save info about files on my D:
drive using code:
private void ListDirectory(TreeView treeView, string path)
{
var rootDirectoryInfo = new DirectoryInfo(path);
treeView.Items.Add(CreateDirectoryNode(rootDirectoryInfo));
}
private static TreeViewItem CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeViewItem();
directoryNode.Header = directoryInfo.Name;
try
{
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Items.Add(CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles())
directoryNode.Items.Add(new TreeViewItem { Header = file.Name });
}
catch (UnauthorizedAccessException e)
{ }
return directoryNode;
}
It works fine, and TreeView
shows all the folders and files. Please, show me how to save data from TreeView
to XML
. Thanks.
Tried this:
public void exportToXml(TreeView tv, string filename)
{
sr = new StreamWriter(filename, false, System.Text.Encoding.UTF8);
//Write the header
sr.WriteLine("<?xml version="1.0" encoding="utf-8" ?>");
//Write our root node
sr.WriteLine("<ROOT>");
foreach (TreeViewItem node in tv.Items)
{
saveNode(node.Items);
}
//Close the root node
sr.WriteLine("</ROOT>");
sr.Close();
}
private void saveNode(TreeViewItem[] tnc)
{
foreach (TreeViewItem node in tnc)
{
//If we have child nodes, we'll write
//a parent node, then iterrate through
//the children
if (node.Items.Count > 0)
{
sr.WriteLine("<" + node.Name + ">");
saveNode(node.Items);
sr.WriteLine("</" + node.Name + ">");
}
else //No child nodes, so we just write the text
sr.WriteLine(node.Name);
}
}
But saveNode(node.Items);
says that there are different types between node.Items
and TreeViewItem[]
, so I tried List<TreeViewItem>
, but error is the same.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…