Isaiah Nelson
Isaiah Nelson

Reputation: 2490

How do I use LINQ to parse XML with child elements of the same name?

Background Information: In the past, I have been picking up a collection of XML files and iterating through each XML file, parsing it, passing string data to a data transfer object and passing the object into a database.

Before, my XML looked like this.

<messages>
    <message>
        <title>Red Wall</title>
        <summary>This is a good article</summary>
        <ISBN>13546846545464</ISBN>
    </message>
</messages>

Here, I only have one element. So, I would parse the XML by using LINQ and retrieve the subsequent elements(title, summary, isbn). Then I would initialize/instantiate an object, assign its properties to the values I retrieved, and send it along.

Now my XML looks like this:

<messages>
<message>
    <title>Red Wall</title>
    <summary>This is a good article</summary>
    <ISBN>13546846545464</ISBN>
</message>

<message>
    <title>Blue Wall</title>
    <summary>This is not a good article</summary>
    <ISBN>15648465416</ISBN>
</message>
</messages>

I now have two (or more) elements in my XML file, and for each one I need to 1) identify that there are multiple elements and 2) for each create a separate DTO to hold the data that I parse.

My question is: How do I parse XML with multiple tags and identify each one I encounter as being separate from the other?

Final Note: While parsing, I need to be able to instantiate a DTO to capture the information I get returned back.

Thanks for helping!

Upvotes: 2

Views: 694

Answers (2)

Josh Rack
Josh Rack

Reputation: 1242

The select statement above is going to return an IEnumerable<DTO>, which is a sequence of DTO objects. For every message node it finds in the XML, it will create a DTO object and add it to the sequence returned. If your goal is just to iterate over all the DTOs, you're already there. If you actually need a List<DTO>, there is a constructor on the generic List object that takes an IEnumerable<T>, so you could pass in the "dtos" you received from the select statement and have a List.

Upvotes: 0

rerun
rerun

Reputation: 25505

Just Grab the element you want and use your select to populate the dto from the child items. Something like this not tested

XElement ele = loaded.Element("messages");    
dtos = from item in ele.Descendants("message")
    select new DTO() {title = item.Element(title).value ,... };

Upvotes: 2

Related Questions