Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Windows.Forms;
- using System.Drawing;
- using System.Xml;
- namespace XmlToTreeview
- {
- public class Form1 : Form
- {
- TreeView treeView1 = new TreeView();
- Boolean expanded = true;
- public static void Main(string[] args)
- {
- try
- {
- Application.Run(new Form1());
- }
- catch (Exception e)
- {
- Console.WriteLine(e.Message);
- }
- }
- // https://pastebin.com/PGVHnWqs
- /*
- https://ourcodeworld.com/articles/read/913/how-to-render-a-xml-file-string-into-a-treeview-component-in-winforms-with-csharp
- https://stackoverflow.com/questions/8503521/populating-treeview-from-xml
- https://stackoverflow.com/questions/28491166/parse-xml-to-treeview-list
- http://www.thescarms.com/dotnet/XMLTreeview.aspx
- */
- public Form1()
- {
- FileStream fs = new FileStream(@"xml_to_treeview.xml", FileMode.Open, FileAccess.Read);
- Size = new Size(300, 600);
- Text = fs.Name;
- Controls.Add(treeView1);
- treeView1.Dock = DockStyle.Fill;
- treeView1.NodeMouseDoubleClick += new TreeNodeMouseClickEventHandler(TreeView1NodeMouseDoubleClick);
- XmlDocument xmlDoc = new XmlDocument();
- XmlNode xmlnode;
- xmlDoc.Load(fs);
- xmlnode = xmlDoc.ChildNodes[1];
- treeView1.Nodes.Clear();
- treeView1.Nodes.Add(new TreeNode(xmlDoc.DocumentElement.Name));
- AddNode(xmlnode, treeView1.Nodes[treeView1.Nodes.Count - 1]);
- fs.Close();
- }
- private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
- {
- // Attribútumok listázása:
- if (inXmlNode.Attributes != null)
- {
- foreach (XmlAttribute attrib in inXmlNode.Attributes)
- {
- inTreeNode.Nodes.Add(new TreeNode("[ " + attrib.Name + "= '" + attrib.Value + "' ]"));
- }
- }
- // Elemek listázása:
- // Az '... || inXmlNode.InnerText.Trim().Equals("") ' nélkül az üres elem tartalma, azaz a "" felülírja az elem nevét a fában!
- if (inXmlNode.HasChildNodes || inXmlNode.InnerText.Trim().Equals(""))
- {
- foreach (XmlNode xxNode in inXmlNode.ChildNodes)
- {
- inTreeNode.Nodes.Add(new TreeNode(xxNode.Name));
- AddNode(xxNode, inTreeNode.Nodes[inTreeNode.Nodes.Count - 1]);
- }
- }
- else
- {
- inTreeNode.Text = "'" + inXmlNode.InnerText.ToString() + "'";
- }
- }
- private void TreeView1NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
- {
- treeView1.BeginUpdate();
- if (expanded)
- {
- treeView1.CollapseAll();
- expanded = false;
- }
- else
- {
- treeView1.ExpandAll();
- expanded = true;
- }
- treeView1.EndUpdate();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement