C# 中的类到 XML
我有一个 C# 类,如下所示:
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;
}
}
并且,我有一个 List、ModuleName、BlocksCovered/BlocksNotCovered 变量。 根据这些信息,我需要创建一个 XML 文件,如下所示。
<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>
我怎样才能用 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#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于这样一个简单的情况,我将使用带有 XML 序列化属性的
XmlSerializer
。这里提供了一个很好的教程:
http://www.codeproject.com/KB/XML/ GameCatalog.aspx
我强烈建议您使用属性而不是成员,因为您将来在实现挂钩或区分获取/设置访问权限时会更加灵活。 (但是,如果您仍然想使用 XML 属性,则后者必须保持公开,否则您必须切换到实现
IXmlSerialized
。)将如下所示:
在您的情况下,代码 由
XmlSerializer
完成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:
The job is then done by the
XmlSerializer
您可以使用xsd.exe(随 Visual Studio 提供)从 xml 文件生成类(如果您有 xsd 文件,那就更好了)。命令是:
然后,只需创建要保存为 xml 的对象列表并执行类似的操作:
其中coverageInfo 是
List
和 GetEntityXml1是:1 信用 其中信用到期。
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:
Then, just create the list of objects you want saved as an xml and do something similar to this:
where coverageInfo is a
List<CoverageInfo>
and GetEntityXml1 is:1 Credit where credit is due.