Parsing XMl with unknown tag names in C#



I am trying to parse xml to a stringbuilder in C#. But the XML file has un-determined tag names inside. I don't want to put element names by using xdoc.elements("tagName"). I wish I can dynamically loop through the XML file.


The XML I have is like this:



<userInfo>
<name> Gummy Bear </name>
<age> 1 </age>
</userInfo>

<userInfo>
<name> Dorito </name>
<Email> IloveDorito@gmail.com </email>
<hobby> eating Doritos </hobby>
</userInfo>


As you have seen in the sample file, the only tag in common for each user is <userInfo>


The ideal output would be grouped by each user:


Gummy Bear, 1,


Dorito,IloveDorito@gmail.com,eating Doritos


I have the following code but it combines all the elements under one user into one line.



StringBuilder result = new StringBuilder();
XDocument xdoc = XDocument.Load(@"test.xml");
var userNode = xdoc.Root.Elements("userInfo");
foreach(var d in userNode)
{
result.append(d.value):
}
MessageBox.show (result+"");

No comments:

Post a Comment