Dictionary to XML using LINQ

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • maylortaylor
    New Member
    • Nov 2012
    • 72

    Dictionary to XML using LINQ

    So I have a function that takes in a Dictionary and returns a XML document with the information. It uses LINQ which I suck at and would like some help reformat the information.

    So far the information comes out like this:

    Code:
    <UserClassDictionary>
       <adolan>
          <ControlNumber>791301</ControlNumber>
       </adolan>
       <afeazell>
          <ControlNumber>790253</ControlNumber>
       </afeazell>
       <asnyder>
          <ControlNumber>790210</ControlNumber>
          <ControlNumber>790308</ControlNumber>
    </UserClassDictionary>
    However, I wish to have the format look like this.

    Code:
    <user name="adolan">
    <controlNumbers>
    <number>123</number>
    <number>546</number>
    </controlN​umbers>
    </user>

    Here is the function thus far.

    Code:
     static void DictionaryToXML(Dictionary<string,User> UserClassDict)
            {
                string xmldoc = "UserClassDictionary.xml";
                Console.WriteLine("Moving User Dictionary data to XML (" + xmldoc + ")...");
    
                XElement el = new XElement("UserClassDictionary",
           UserClassDict.Select(kv => new XElement(kv.Key,
                        kv.Value.ControlNumber.Select(num => new XElement("ControlNumber", num)))));
    
                var xml = el.ToString();
                File.WriteAllText(xmldoc, xml);
            }
Working...