Skip to content

Instantly share code, notes, and snippets.

@Nasawa
Created July 13, 2015 20:28
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Nasawa/45509753d5ad27245b40 to your computer and use it in GitHub Desktop.
Convenient way of turning XML into a TreeNode for a Windows Forms TreeView
public static TreeNode ToTreeNode(XmlDocument doc, string root = "root")
{
TreeNode node = new TreeNode(root);
Nodify(node, doc.DocumentElement);
return node;
}
public static TreeNode ToTreeNode(string filename, string root = "root")
{
var x = new XmlDocument();
x.Load(filename);
return ToTreeNode(x, root);
}
private static void Nodify(TreeNode parent, XmlNode node)
{
if (node.Attributes != null)
foreach (XmlAttribute attr in node.Attributes)
{
TreeNode t = new TreeNode(attr.Name);
t.Nodes.Add(attr.Value);
parent.Nodes.Add(t);
}
if (node.HasChildNodes)
{
foreach (XmlNode child in node.ChildNodes)
{
TreeNode newNode = parent.Nodes.Add(child.Name);
Nodify(newNode, child);
}
}
else
{
parent.Text = node.Name == "#text" ? node.OuterXml.Trim() : node.Name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment