It all depends on the structure of the source XML and on the form in which you need to get the data.
Suppose there is a document with information about people of the following content:
<Persons> <Person id="1"> <FirstName>Вася</FirstName> <LastName>Пупкин</LastName> <Address Country="РФ"> <City>Тагил</City> <Street>Ленина</Street> </Address> </Person> <Person id="007"> <FirstName>James</FirstName> <LastName>Bond</LastName> <Address Country="UK"> <City>London</City> <Street>Lennon</Street> </Address> </Person> </Persons>
Apply classic tree traversal:
void WalkTree(TreeNodeCollection nodes, XElement element) { if (element.HasElements) { var node = nodes.Add(element.Name.LocalName); foreach (var attr in element.Attributes()) node.Nodes.Add(attr.Value); foreach (var elem in element.Elements()) WalkTree(node.Nodes, elem); } else nodes.Add(element.Value); }
We use:
var doc = XDocument.Load("test.xml"); WalkTree(treeView.Nodes, doc.Root); treeView.ExpandAll();
In this case, I take the name of the elements that have descendants, and then pass on their descendants. And for each leaf element that has no descendants, I bring up the value in the tree. Attributes are equivalent to leaf elements.
You can vary the code as you like.