EXTENSION METHOD FOR Xml SERIALIZING AND DESERIALIZING C#, LIST AND GENERIC ARRAY FOR CODE REVIEW

Asked 2 years ago, Updated 2 years ago, 47 views

I wrote an extension method to Xml serialize and de-serialize List and T[] in C# myself, but I would like you to point out how to handle exceptions (whether it is defined by the user or by the user) and how to write them.Thank you for your cooperation.

//<summary>Methods to load Xml into a generic array</summary> 
    public static void LoadXml<T> (this T[] list, string path)
    {
        T[]xmldata=null;

        XmlDocument xdoc = new System.Xml.XmlDocument();
        XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(typeof(T[])));

        xdoc.PreserveWhitespace=true;
        xdoc.Load (path);

        XmlNodeReader xnr = new System.Xml.XmlNodeReader(xdoc.DocumentElement);

        xmldata=(T[])xml.Deserialize(xnr);

        for (inti=0;i<xmldata.Length;i++)
            list[i] = xmldata[i];
    }

    // <summary> Methods to load Xml into List<T>
    public static void LoadXml<T> (this List<T>list, string path)
    {
        list.Clear();

        T[]xmldata=null;

        XmlDocument xdoc = new System.Xml.XmlDocument();
        XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(typeof(T[])));

        xdoc.PreserveWhitespace=true;
        xdoc.Load (path);

        XmlNodeReader xnr = new System.Xml.XmlNodeReader(xdoc.DocumentElement);

        xmldata=(T[])xml.Deserialize(xnr);

        for (inti=0;i<xmldata.Length;i++)
            list.Add(xmldata[i]);
    }

    /// <summary> Method for saving generic arrays to Xml</summary>
    public static void SaveXml<T> (this T[] list, string path)
    {
        T[]xmldata=null;
        xmldata=list.ToArray();

        using(FileStreamfs=newFileStream(path,FileMode.Create))
        {
            XmlSerializer xml = new XmlSerializer(typeof(T[]);

            xml.Serialize(fs,xmldata);
        }
    }

    /// <summary>List>T>Methods for Saving Objects to Xml</summary>
    public static void SaveXml<T> (this List<T>list, string path)
    {
        T[]xmldata=null;
        xmldata=list.ToArray();

        using(FileStreamfs=newFileStream(path,FileMode.Create))
        {
            XmlSerializer xml = new XmlSerializer(typeof(T[]);

            xml.Serialize(fs,xmldata);
        }
    }
}

c#

2022-09-30 19:12

2 Answers

First, SaveXml, but it is redundant and barren to write two versions: T[] and List<T>.The code can be unified by making it an extension method for interfaces that both classes implement in common.
Similarly, LoadXml is redundant with two versions, but prior to that, T[] and List>T> are not meaningful in requesting the first argument and should create a new object and return it.In other words, the extension method itself is inappropriate.
With these in mind, can you describe it as follows?

public static class XmlUtil{
    public static T[] LoadFrom <T>(string path){
        varserializer = new XmlSerializer(typeof(T[]));
        using(var stream=File.OpenRead(path))
            return(T[])serializer.Deserialize(stream);
    }

    public static void SaveTo<T> (this IEnumerable<T>source,string path) {
        varserializer = new XmlSerializer(typeof(T[]));
        using(var stream=File.OpenWrite(path))
            serializer.Serialize(stream, source as T[]?source.ToArray());
    }
}

I didn't know what you were concerned about handling exceptions.
In addition to the XmlSerializer, there are DataContractSerializer and the serialization method is different, but the user has no choice.It's not limited to this, but the responsibility of how it's serialized is on the method side, and the user can't control it. Is that okay?


2022-09-30 19:12

XmlSerializer takes the type of one-way access, such as XmlReader, or TextReader or Stream.This internally processes XML nodes from top to bottom, indicating that access to the entire XML document is unnecessary.

On the other hand, XmlDocument is a class that provides free operation for the entire XML document, so memory usage and initialization take longer in general than XmlReader.

Therefore, you should avoid unnecessarily instantiating XmlDocument.XmlReaderSettings.IgnoreWhitespace corresponding to XmlDocument.PreserveWhitespace is false by default, so do not specify any special options

XmlReader xnr=XmlReader.Create(path);

can be replaced with .As mentioned above, XmlSerializer.Deserialize accepts Stream and TextWriter, so you can use FileStream or StreamReader instead of XmlReader.

Also, exception handling should be considered, including recovery in the event of an error.For example, if you need to do something specific to this method, such as "Write again after 1 second and fail 10 times as an error", you may need to do an exception within SaveXml, but if you don't have one, you should do something generic.


2022-09-30 19:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.