Sorting the output from XmlSerializer in C#
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);
WriteFi开发者_JAVA百科leStream.Close();
SOLVED
public void Sort()
{
ClassInfoList = ClassInfoList.OrderBy( x=>x.CoverageRate).ToList();
}
Just sort your list before serializing, it appears in your code that you have control over the serialization - if that is the case just sort the ClassInfoList
list before serializing your Module by adding a Sort()
method:
public class Module
{
public void Sort()
{
ClassInfoList = ClassInfoList.OrderBy( x=>x.BlocksCovered).ToList();
}
..
}
then call Sort() before serializing:
report.Sort();
ser.Serialize(WriteFileStream, report, ns);
If you don't have control over when/and how your class is serialized have your Module class implement IXmlSerializable
and sort within your Serialize()
method - the later is more effort though and should be avoided.
精彩评论