So if I have XML that looks something like this....
<people>
<person>
<name>a</name>
</person>
<person>
<name>b</name>
</person>
</people>
What's the best/easiest way to parse this into a C# array called 'people' where people[0] is the first person object, and then how would it be formatted and how would I go about accessing it?
Thanks!
My C# is rusty, but this is simple enough using XML serialization
Deserializing (reading), modifying, then serializing (writing):
If the input xml format is as simple as the one you provided the above statement is sufficient, otherwise add this where clause to not capture other
name
elements in your xml file:You could use LINQ-To-Xml to load this file into an array.
To simply handle the object after loading them you could create a class representing a person:
Then load the file using the
XElement.Load
-method:You can do it easily with LinqToXml:
It will return you an array of
Person
's defined as below.Person
Assuming:
Then (query syntax):
The same in Extension Methods syntax:
One line is enough.
You need to specify following namespaces for testing
test code
the sample xml for test