I have assigned a XMLNodeList and its child nodes collection to a Treeview.. I get to see all the data on the treeview..
Now i select a treeview node item. I now want to get the XMLNode associated with it. Basically i want开发者_运维问答 the conversion from a TreeNode ---> XMLNode Is this possible ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace XmlIntrospection
{
public partial class Form1 : Form
{
public class XmlNodeTree : TreeNode
{
private XmlNode mNode;
public XmlNode Node
{
get { return mNode; }
}
public XmlNodeTree(XmlNode node)
{
mNode = node;
if (node.NodeType == XmlNodeType.Text)
{
Text = node.InnerText;
}
else
{
Text = node.Name;
}
if (node.Attributes != null)
{
foreach (XmlAttribute a in node.Attributes)
{
Text += " " + a.OuterXml;
}
}
}
}
private XmlDocument doc;
public Form1()
{
InitializeComponent();
doc = new XmlDocument();
}
/// <summary>
/// Fill the tree View with xml Node recurcively
/// </summary>
/// <param name="c"> current Tree node </param>
/// <param name="l"> current xml node </param>
private void FillTreeView(TreeNodeCollection c,XmlNodeList l)
{
if (l == null)
{
return;
}
foreach (XmlNode e in l)
{
XmlNodeTree n = new XmlNodeTree(e);
c.Add(n);
FillTreeView(n.Nodes, e.ChildNodes);
}
}
private void Init()
{
treeView1.Nodes.Clear();
textBox1.Text = "";
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
Init();
doc.Load(openFileDialog1.FileName);
XmlNodeTree root = new XmlNodeTree(doc.LastChild);
textBox1.Text = doc.InnerXml;
treeView1.Nodes.Add(root);
FillTreeView(root.Nodes,doc.LastChild.ChildNodes);
}
catch
{
MessageBox.Show("File " + openFileDialog1.FileName + " no valid xml file");
}
}
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
XmlNodeTree currentNode = (XmlNodeTree) e.Node;
propertyGrid1.SelectedObject = currentNode.Node;
}
}
}
精彩评论