Matt
Matt

Reputation: 26971

Writing XML document containing multiple objects in C#

I have a few objects in my class

List<string> a
List<string> b
Dictionary<string,string> c

I want a resulting XML document that contains the data contained in these three object so that it would look like:

<myobject>
    <as>
     <a value="xxxxx" />
     <a value="xxxxx" />
     <a value="xxxxx" />
    </as>
    <bs>
     <b value="xxxxx" />
     <b value="xxxxx" />
     <b value="xxxxx" />
    </bs>
    <cs>
     <c key="x" value="xxxxx" />
     <c key="x" value="xxxxx" />
     <c key="x" value="xxxxx" />
    </cs>
</myobject>

What is the most appropriate technique to use here? Should I just iterate through each object or is there an easier way to do this? Tere are a few XML writers in .Net and I'm unsure which to use. Is XML serialization the better way to go?

Upvotes: 1

Views: 273

Answers (1)

Chris Wenham
Chris Wenham

Reputation: 24017

using System.Linq;
using System.Xml.Linq;

...

XDocument doc = new XDocument(
    new XElement("as",
        a.Select(item => new XElement("a",
           new XAttribute("value", item)
        )
    ),
    new XElement("bs",
        b.Select(item => new XElement("b",
           new XAttribute("value", item)
        )
    ),
    new XElement ("cs",
        c.Select(item => new XElement("c",
           new XAttribute("key", item.Key),
           new XAttribute("value", item.Value)
        )
    )
);

Upvotes: 3

Related Questions