1

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?

1
  • 3
    XmlSerializer won't know how to serialize Dictionary<string, string> without implementing IXmlSerializable or something like that. Commented Mar 30, 2011 at 23:38

1 Answer 1

3
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)
        )
    )
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.