[Solved] Parsing xml in string [duplicate]


I’d use LINQ to XML, with a helper method:

var movies = from element in XDocument.Parse(xml).Descendants("Movie")
             select new Class1
             {
                 Id = (int) element.Attribute("ID"),
                 Subject = (string) element.Element("Name"),
                 OtherName = (string) element.Element("OtherName"),
                 Duration = (int) element.Element("Duration")
                                         .Attribute("Duration"),
                 Property1 = (string) element.Element("Properties")
                     .Elements("Property")
                     .Where(x => (string) x.Attribute("Name") == "Property1")
                     .Single(),
                 Property2 = (string) element.Element("Properties")
                     .Elements("Property")
                     .Where(x => (string) x.Attribute("Name") == "Property2")
                     .Single(),
                 Subject = (string) element.Element("Name"),
             };

If there are really a lot of Property elements, you might want to turn them into a dictionary:

Properties = element.Element("Properties")
                    .Elements("Property")
                    .ToDictionary(x => (string) x.Attribute("Name"),
                                  x => (string) x);

solved Parsing xml in string [duplicate]