简体   繁体   中英

Storing and retrieving data from an XML file

I storage a set of user provided data in a file. When I took over the project, everything was saved to a plain text file. I redesigned it and now, the storage is an XML file. When the process starts, I read the XML file using XDocument and XElement classes. When I've obtained the values I put them in a constructor of my executing object.

I wonder if there's a way to automagically read in the XML data so that it, sort of, transforms (or is converted to) an instance of my object.

So, instead of:

XElement fromFile = XElement.Load(pathName);
XElement newStuff =
  new XElement("MainNode",
    new XElement("SubNode1", myObject.valueOfSubNode1),
    new XElement("SubNode2", myObject.valueOfSubNode2));
fromFile.ReplaceAll(newStuff);

XmlTextWriter writer = ...;
fromFile.Save(writer);

I'd like to "store" the instance of myObject itself. I'm assuming that's possible. I have no idea how or even where to start.

to serialize a type to XML:

public static string Serialize<T>(T data)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

    StringWriter sw = new StringWriter();
    xmlSerializer.Serialize(sw, data);
    return sw.ToString();
}

to deserialize from XML back into your object:

public static object DeSerialize<T>(string data)
{
  StringReader rdr = new StringReader(data);

  XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

  var result = (T)xmlSerializer.Deserialize(rdr);

  return result;
}

also have a look here: C# XML Serialization/DeSerialization

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM