I have written a code that reads an XMl
file and then construct a tree view of XML
file using the nodes name. I would like to know how could I have attributes instead of the components(nodes) name?
For example, in the following XML
file instead of action
(s) I would like to print in the tree view copy
or paste
, etc, except for the first two parent nodes (Report
and test
).
XML
file:
<Report version="2.1" xmlns="http://www.froglogic.com/XML2">
<test name="Example">
<action name="delet">
this is delet
</action>
<action name="copy">
this is copy
</action>
<action name="paste">
this is paste
</action>
<action name="manipulate">
this is manipulate
</action>
<action name="copy">
this is copy
</action>
<action name="paste">
this is paste
</action>
<action name="manipulate">
this is manipulate
</action>
<action name="change">
this is change
</action>
</test>
</Report>
and the C#
code:
private void File2_load(object sender, EventArgs e)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(File2Path.Text);
treeView2.Nodes.Clear();
treeView2.Nodes.Add(new TreeNode(doc.DocumentElement.Name));
TreeNode tNode = new TreeNode();
tNode = treeView2.Nodes[0];
AddNode(doc.DocumentElement, tNode);
treeView2.ExpandAll();
treeView2.CheckBoxes = true;
}
catch (XmlException xmlEx)
{
MessageBox.Show(xmlEx.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Update
private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
{
XmlNode xNode;
TreeNode tNode;
XmlNodeList nodeList;
int i;
if (inXmlNode.HasChildNodes)
{
nodeList = inXmlNode.ChildNodes;
for (i = 0; i <= nodeList.Count - 1; i++)
{
xNode = inXmlNode.ChildNodes[i];
inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
tNode = inTreeNode.Nodes[i];
AddNode(xNode, tNode);
}
}
else
{
inTreeNode.Text = (inXmlNode.OuterXml).Trim();
}
}