Xml document, you need to recreate the object by its structure

  • Each Chapter element has a Position.
  • Position has one element Resources.
  • Resources has Tzr and Mat, but not in every Position.

Classes create such

class Position { public string Caption { get; set; } public string Quantity { get; set; } public List<Tzr> tzrCollection { get; set; } } class Chapter { public string Caption { get; set; } public int Age { get; set; } public List<Position> positions { get; set; } } class Tzr { public string Caption { get; set; } } 

The question is how to get to tzr or mat, if there are Positions without a mat or tzr? If you handle crookedly (my way) - it returns an error

  XDocument doc = XDocument.Load("Data.xml"); var chapters = from c in doc.Element("Document").Element("Chapters").Elements("Chapter") select new Chapter { Caption = c.Attribute("Caption").Value, positions = (from p in c.Elements("Position") select new Position { Caption = p.Attribute("Caption").Value, Quantity = p.Attribute("Quantity").Value, tzrCollection = (from t in p.Element("Resources").Elements("Mat") where t != null select new Tzr { Caption = t.Attribute("Caption").Value }).ToList() }).ToList() }; 
  • one
    Example xml show - Ev_Hyper

1 answer 1

Xml document, you need to recreate the object by its structure

This is called deserialization.

In your case, you need to fully describe the structure of the xml-file, that is, add another Document class:

  public class Document { public List<Chapter> Chapters { get; set; } } 

Further we deserialize:

  XmlSerializer serializer = new XmlSerializer(typeof(Document)); XmlTextReader xr = new XmlTextReader(@"path\to\Data.xml"); Document doc = (Document)serializer.Deserialize(xr); // получаем объект из xml List<Chapter> chapters = doc.Chapters; // получаем список объектов Chapter