deserialize `Dictionary<string, Tuple<string, List<string>>>` from custom XML using XElement

247 views Asked by At

I have a Dictionary<string, Tuple<string, List<string>>> email in which i want to write to XML (Serialize) and also load from XML to Dictionary.

I got the write to XML as such:

public void WritetoXML(string path) {
  var xElem = new XElement(
    "emailAlerts",
    email.Select(x => new XElement("email", new XAttribute("h1", x.Key),
                 new XAttribute("body", x.Value.Item1),
                 new XAttribute("ids", string.Join(",", x.Value.Item2))))
                 );
  xElem.Save(path);
}

But i'm stuck on LoadXML where it takes the XML path and loads it into the dictionary inside this Email Class

This is what i have so far:

public void LoadXML(string path) {
  var xElem2 = XElement.Parse(path);
  var demail = xElem2.Descendants("email").ToDictionary(x => (string)x.Attribute("h1"),
               (x => (string)x.Attribute("body"),
                x => (string)x.Attribute("body")));
}

Background information My XML should be something like this

<emailAlerts>
   <email h1='Test1' body='This is a test' ids='1,2,3,4,5,10,11,15'/>
</emailAlerts>
2

There are 2 answers

1
har07 On

You can try this way :

public void LoadXML(string path) 
{
   var xElem2 = XElement.Load(path);
   var demail = xElem2.Descendants("email")
                      .ToDictionary(
                            x => (string)x.Attribute("h1")
                            , x => Tuple.Create(
                                        (string)x.Attribute("body") 
                                        , x.Attribute("ids").Value
                                                            .Split(',')
                                                            .ToList()
                                    )
                        );
}
  • if path parameter contains path to XML file, then you should've used XElement.Load(path) instead of XElement.Parse(path).
  • using Tuple.Create() to construct Tuple instance is often shorter than new Tuple() style
0
Alexandre Perez On

Try this:

var str = @"<emailAlerts>
                <email h1='Test1' body='This is a test' ids='1,2,3,4,5,10,11,15'/>
            </emailAlerts>";    

var xml = XElement.Parse(str);


var result = xml.Descendants("email").ToDictionary(
    p => p.Attribute("h1").Value, 
    p => new Tuple<string, List<string>>(
        p.Attribute("body").Value, 
        p.Attribute("ids").Value.Split(',').ToList()
    )
);