Sorting the output from XmlSerializer in C#

Posted by prosseek on Stack Overflow See other posts from Stack Overflow or by prosseek
Published on 2011-03-07T23:53:04Z Indexed on 2011/03/08 0:10 UTC
Read the original article Hit count: 167

Filed under:
|
|
|

In this post, I could get an XML file generated based on C# class.

Can I reorder the XML elements based on its element? My code uses

var ser = new XmlSerializer(typeof(Module));
ser.Serialize(WriteFileStream, report, ns);
WriteFileStream.Close();

to get the XML file, but I need to have the XML file sorted based on a BlocksCovered variable.

public class ClassInfo {
    public string ClassName;
    public int BlocksCovered;
    public int BlocksNotCovered;
    public double CoverageRate;

    public ClassInfo() {}

    public ClassInfo(string ClassName, int BlocksCovered, int BlocksNotCovered, double CoverageRate) 
    {
        this.ClassName = ClassName;
        this.BlocksCovered = BlocksCovered;
        this.BlocksNotCovered = BlocksNotCovered;
        this.CoverageRate = CoverageRate;
    }
}

[XmlRoot("Module")]
public class Module {
    [XmlElement("Class")]
    public List<ClassInfo> ClassInfoList;
    public int BlocksCovered;
    public int BlocksNotCovered;
    public string moduleName;

    public Module()
    {
        ClassInfoList = new List<ClassInfo>();
        BlocksCovered = 0;
        BlocksNotCovered = 0;
        moduleName = "";
    }
}

Module report = new Module();

...

TextWriter WriteFileStream = new StreamWriter(xmlFileName);
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
var ser = new XmlSerializer(typeof(Module));
ser.Serialize(WriteFileStream, report, ns);
WriteFileStream.Close();

© Stack Overflow or respective owner

Related posts about c#

Related posts about Xml