Convenient way of turning XML into a TreeNode for a Windows Forms TreeView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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