Peer

Peer

  • NA
  • 9
  • 3.7k

Mapping TreeView to/from xmldoc

Apr 6 2011 8:29 AM

Hi,
Developing a trad win app using VS 2010 C#.

Starting from loading a xml file into a XMLDocument object.

openedFile = someFile.xml;

xmlReader = new XmlTextReader(openedFile);

Global.mainXMLDoc.Load(xmlReader);

xmlReader.Close();

 

private void AddNodeToTreeView(ref XmlNode inXmlNode, ref TreeNode inTreeNode)

{

XmlNode xNode;

TreeNode tNode;

XmlNodeList nodeList;



if (inXmlNode.HasChildNodes)

{

nodeList = inXmlNode.ChildNodes;

for (int i = 0; i <= nodeList.Count - 1; i++)

{

xNode = inXmlNode.ChildNodes[i];

inTreeNode.Nodes.Add(new TreeNode(xNode.Name));

tNode = inTreeNode.Nodes[i];

AddNodeToTreeView(ref xNode, ref tNode);

}

}

}

 



Now I have a multi column ListView to show the attributes whenever user selects a node from the TreeView component. Here's where it all gets totally wrong. My first idea was to use the tv.SelectedNode.Index (in the TreeView event listener _AfterSelect). But since this index is calculated relatively its parent the mapping to the xmlNodes is lost.

private void treeView_AfterSelect(object sender, TreeViewEventArgs e, TreeView tv, ListView lv)

{

lv.Items.Clear();

ListViewItem lvItem;

currentNodeName = tv.SelectedNode.Text;

int currentNodeIx = tv.SelectedNode.Index;

xmlNodes = Global.mainXMLDoc.GetElementsByTagName(currentNodeName);

XmlNode xNode = xmlNodes.Item(currentNodeIx);

string attr;

string val;



for (int i = 0; i < xNode.Attributes.Count; i++)

{

attr = xNode.Attributes[i].Name;

val = xNode.Attributes[i].Value;

lvItem = new ListViewItem(attr);

string foo = FindXPath(xNode.Attributes[i]);

lvItem.SubItems.Add(val);

lvItem.SubItems.Add(foo);

lv.Items.Add(lvItem);

}

}
So, is there a way you can do this using these standard components or do I need to design my own?

Cheers!

Answers (8)