v.g.
v.g.

Reputation: 1076

How to get inner xml from string containing XMl

So if I have this sample string with xml within.

"<bookstore>
   <book genre='autobiography' publicationdate='1981-03-22' ISBN='1-861003-11-0'>
       <title>The Autobiography of Benjamin Franklin</title>
       <author age="40">
           <first-name>Benjamin</first-name>
           <last-name>Franklin</last-name>
       </author>
       <author age="56">
           <first-name>Barack</first-name>
           <last-name>Obama</last-name>
       </author>
       <price>8.99</price>
   </book>
 </bookstore>"

I want from it to make two different strings as follows:

"<author age="40">
           <first-name>Benjamin</first-name>
           <last-name>Franklin</last-name>
       </author>"

and

"<author age="56">
           <first-name>Barack</first-name>
           <last-name>Obama</last-name>
       </author>"

because I want to put them in List. I tried using Split but with no result

Upvotes: 2

Views: 335

Answers (1)

Jonesopolis
Jonesopolis

Reputation: 25370

You could do this in one line with LINQ:

List<string> list = XDocument.Parse(xmlString)
                     .Descendants("author")
                     .Select(x => x.ToString())
                     .ToList();

Upvotes: 6

Related Questions