我正在用c#创建一个模型,我的想法是稍后我正在做的应用程序将从xml读取数据并将其转换为对象,但是我想生成一个示例xml。我怎么能这样做?
我的样本c#类是:
public class SiteDefinition
{
public string Name { get; set; }
public string Version { get; set; }
public List<MasterPage> MasterPages { get; set; }
public List<File> Files { get; set; }
public List<PageLayout> PageLayouts { get; set; }
public List<Feature> Features { get; set; }
public List<ContentType> ContentTypes { get; set; }
public List<StyleSheet> StyleSheets { get; set; }
}
答案 0 :(得分:1)
var instance = new SiteDefinition();
var serializer = new XmlSerializer(typeof(SiteDefinition));
using(var writer = new StreamWriter("C:\\Path\\To\\File.xml"))
{
serializer.Serialize(writer, instance);
}
如果你想自定义输出(属性等),你可以使用许多属性来装饰你的类和类成员。查看this MSDN article for more info
答案 1 :(得分:1)
XML序列化
必需的命名空间
using System.Xml.Serialization;
以XML格式读写类
public static List<SiteDefinition> Read()
{
XmlSerializer reader = new XmlSerializer(typeof(List<SiteDefinition>));
using (FileStream file = File.OpenRead(Path.Combine(Global.AppRoot, configFileName)))
{
return reader.Deserialize(file) as List<SiteDefinition>;
}
}
public static void Write(List<SiteDefinition> settings)
{
XmlSerializer writer = new XmlSerializer(typeof(List<SiteDefinition>));
using (FileStream file = File.Create(Path.Combine(Global.AppRoot, configFileName)))
{
writer.Serialize(file, settings);
}
}