Julien Pierre
Julien Pierre

Reputation: 467

How to parse multiple single xml elements in .Net C#

I'm trying to deserialise some xml that contains multiple single xml elements in .Net C#, like so:

<Root>
 <Status>OK</Status>
 <Person>
  <Name>Element 1</Name>
 </Person>
 <Person>
  <Name>Element 2</Name>
 </Person>
</Root>

The Person nodes are not in a <Persons></Persons>, therefore I cannot use the [XmlArray] attribute.

Does anyone know to do that, without having to use the XPath with XDocument.

Thanks

Upvotes: 2

Views: 2753

Answers (1)

Saqib
Saqib

Reputation: 7432

If using .Net 3.5 or above, use Linq-to-XML:

string xml = "<root>...</root>";
XDocument doc = XDocument.Parse(xml); // Use .Load() if loading from a file
String status = doc.Root.Element("status").Value;
IEnumerable<string> personNames = doc.Root.Descendants("person").Select(x => x.Element("name").Value);

Upvotes: 1

Related Questions