@LooBi , Welcome to Microsoft Q&A, you could try to use XDocument to get the get attribute value from the xml.
Code:
public string FileName { get; set; }
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "XML Files (*.xml)|*.xml";
if (dlg.ShowDialog() == DialogResult.OK)
{
try
{
this.Cursor = Cursors.WaitCursor;
XmlDocument xDoc = new XmlDocument();
xDoc.Load(dlg.FileName);
FileName= dlg.FileName;
tvLabel.Nodes.Clear();
tvLabel.Nodes.Add(new TreeNode(xDoc.DocumentElement.Name));
TreeNode tNode = new TreeNode();
tNode = (TreeNode)tvLabel.Nodes[0];
addTreeNode(xDoc.DocumentElement, tNode);
tvLabel.ExpandAll();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
this.Cursor = Cursors.Default;
}
}
}
private void addTreeNode(XmlNode xmlNode, TreeNode treeNode)
{
XmlNode xNode;
TreeNode tNode;
XmlNodeList xNodeList;
if (xmlNode.HasChildNodes)
{
xNodeList = xmlNode.ChildNodes;
for (int x = 0; x <= xNodeList.Count - 1; x++)
{
xNode = xmlNode.ChildNodes[x];
string nodetext = xNode.Name+": ";
Console.WriteLine(nodetext);
if(!nodetext.Contains("text"))
{
if (xNode.Attributes.Count>0)
{
for (int i = 0; i < xNode.Attributes.Count; i++)
{
nodetext+=xNode.Attributes[i].Name+" - "+xNode.Attributes[i].Value;
}
}
}
treeNode.Nodes.Add(new TreeNode(nodetext));
tNode = treeNode.Nodes[x];
addTreeNode(xNode, tNode);
}
}
else
{
string nodetext = xmlNode.Name+": ";
Console.WriteLine(nodetext);
if (!nodetext.Contains("text"))
{
if (xmlNode.Attributes.Count>0)
{
for (int i = 0; i < xmlNode.Attributes.Count; i++)
{
nodetext+=xmlNode.Attributes[i].Name+" - "+xmlNode.Attributes[i].Value;
}
}
}
else
{
nodetext=xmlNode.InnerText;
}
treeNode.Text = nodetext;
}
}
Result:
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.