Feedback

C# - Generisch XML De-/ Serialisieren

Veröffentlicht von am 11/20/2009
(3 Bewertungen)
Beispiel Klasse für Serialisierbares Objekt:


public class SimpleData
{
private string name = "";
private string phone = "";

public string Name
{
get { return name; }
set { name = value; }
}
public string Phone
{
get { return phone; }
set { phone = value; }
}
}


Beispiel für Anwendung:


public class SampleUsage
{
private SimpleData data = new SimpleData();

public void LoadSimpleData()
{
data = XMLHelper.DeserializeFromXMLFile[SimpleData](@"simpledata.xml");
}

public void StoreSimpleData()
{
XMLHelper.SerializeToXMLFile[SimpleData](data, @"simpledata.xml", Encoding.Unicode, true);
}

}


Eckige Klammern sind durch spitze Klammern zu ersetzen. (Die eckigen Klammer scheinen hier nicht übernommen zu werden)
public static class XMLHelper
    {
        public static string SerializeToXMLString<T>(T XMLObj, Encoding encoding, bool removeNamespace)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            MemoryStream memStrm = new MemoryStream();
            XmlTextWriter xmlSink = new XmlTextWriter(memStrm, encoding);
            xmlSink.Formatting = Formatting.Indented;

            if (removeNamespace)
            {
                XmlSerializerNamespaces xs = new XmlSerializerNamespaces();
                xs.Add("", "");
                xmlSerializer.Serialize(xmlSink, XMLObj, xs);
            }
            else
                xmlSerializer.Serialize(xmlSink, XMLObj);

            return encoding.GetString(memStrm.ToArray());
        }

        public static void SerializeToXMLFile<T>(T XMLObj, string Filename, Encoding encoding, bool removeNamespace)
        {
            File.WriteAllText(Filename, SerializeToXMLString<T>(XMLObj, encoding, removeNamespace));
        }

        public static T DeserializeFromXMLString<T>(string XML) where T : new()
        {
            T XMLObj = new T();
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            StringReader sr = new StringReader(XML);
            XMLObj = (T)xmlSerializer.Deserialize(sr);
            return XMLObj;
        }

        public static T DeserializeFromXMLFile<T>(string Filename) where T : new()
        {
            if (!File.Exists(Filename))
                throw FileNotFoundException();

            return DeserializeFromXMLString<T>(File.ReadAllText(Filename));
        }

    }
Abgelegt unter XML, Serialize, Generic, Encoding, Namespace.

1 Kommentare zum Snippet

DavidMG schrieb am 5/27/2011:
using System.Text;

throw new FileNotFoundException();
 

Logge dich ein, um hier zu kommentieren!