Class to XML in C#
I have a C# class as follows :
class CoverageInfo {
public string className;
public int blocksCovered;
public int blocksNotCovered;
public CoverageInfo(string className, int blocksCovered, int blocksNotCovered)
{
this.className = className;
this.blocksCovered = blocksCovered;
this.blocksNotCovered = blocksNotCovered;
}
}
And, I have a List, ModuleName, BlocksCovered/BlocksNotCovered variable. Out of those information, I need to create an XML file as follows.
<Coverage>
<Module>
<ModuleName>hello.exe</ModuleName>
<BlocksCovered>5</BlocksCovered>
<BlocksNotCovered>5</BlocksNotCovered>
<Class>
<ClassName>Fpga::hello</ClassName>
<BlockCovered>5</BlocksCovered>
<BlocksNotCovered>2</BlocksNotCovered>
</Class>
<Class>
...
</Class>
</Totalcoverage>
</Coverage>
How can I do开发者_开发技巧 that with C#?
With such a simple case I would use the XmlSerializer
with XML serialization attributes.
A good tutorial is provided here:
http://www.codeproject.com/KB/XML/GameCatalog.aspx
I would urge you to use properties instead of members as you'll be more flexible in implementing hooks or differentiate get/set access rights in the future. (However the latter has to remain public if you still want to use XML attributes or you'll have to switch to implementing IXmlSerializable
.)
The code then would look like this in your case:
class CoverageInfo {
[XmlElement("ClassName")]
public string className;
[XmlElement("BlockCovered")]
public int blocksCovered;
[XmlElement("BlocksNotCovered")]
public int blocksNotCovered;
....
}
The job is then done by the XmlSerializer
i guess this might help: XML to C# Class Question
You can use xsd.exe (provided with Visual Studio) to generate classes from an xml file (if you have the xsd file, it would be even better). The command is:
xsd <path to xsd or xml> /c /o:<path where the cs file is saved>
Then, just create the list of objects you want saved as an xml and do something similar to this:
GetEntityXml(coverageInfo).Save(@"D:\out.xml");
where coverageInfo is a List<CoverageInfo>
and GetEntityXml1 is:
public XmlDocument GetEntityXml<T>(List<T> listToSave)
{
XmlDocument xmlDoc = new XmlDocument();
XPathNavigator nav = xmlDoc.CreateNavigator();
using (XmlWriter writer = nav.AppendChild())
{
XmlSerializer ser = new XmlSerializer(typeof(List<T>), new XmlRootAttribute("Whatever you need"));
ser.Serialize(writer, listToSave);
}
return xmlDoc;
}
1 Credit where credit is due.
精彩评论