如何使用c#从xml获取强类型对象
本文关键字:获取 强类型 对象 xml 何使用 | 更新日期: 2023-09-27 18:02:02
我创建了一个像这样的类模型。
public class SiteDefinition
{
[XmlAttribute ()]
public string Name { get; set; }
[XmlAttribute()]
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; }
}
然后,使用控制台应用程序,我生成了一个xml文件,看起来像这样:
<?xml version="1.0"?>
<SiteDefinition xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Name="ContosoIntranet" Version="1.0.0.0">
<MasterPages>
<MasterPage Url="" Name="seattle.master" LocalFolder=".'seattle.master" ServerFolder="_catalogs/ContosoIntranet/" UIVersion="15" />
</MasterPages>
</SiteDefinition>
我使用的代码:
static void Main(string[] args)
{
var siteDefinition = new SiteDefinition();
siteDefinition.Name = "ContosoIntranet";
siteDefinition.Version = "1.0.0.0";
siteDefinition.MasterPages = new List<SiteProvisioningFramework.MasterPage>()
{
new MasterPage(){
Name="seattle.master",
ServerFolder ="_catalogs/ContosoIntranet/",
UIVersion = "15",
Url="",
LocalFolder = ".MasterPages/seattle.master"
}
};
Utilities.XmlHelper.ObjectToXml(siteDefinition, @".'Sample.xml");
}
我只是想知道xml看起来像什么,在我的应用程序中,用户(开发人员)会给应用程序一个xml文件,然后我想把它转换成一个强类型对象:SiteDefinition
我如何用更少的努力(行)来实现这一点?
private void HandleAppInstalled(SPRemoteEventProperties properties)
{
using (ClientContext cc = TokenHelper.CreateAppEventClientContext(properties, false))
{
if (cc != null)
{
XmlDocument doc = new XmlDocument();
doc.Load(@"/SiteDefinitions/SiteDefinition.xml");
}
}
}
看看下面的
public class SiteDefinition
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
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; }
}
public class MasterPage
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public string ServerFolder { get; set; }
[XmlAttribute]
public string UIVersion { get; set; }
[XmlAttribute]
public string Url { get; set; }
[XmlAttribute]
public string LocalFolder { get; set; }
}
public class StyleSheet
{
}
public class ContentType
{
}
public class Feature
{
}
public class PageLayout
{
}
public class File
{
}
[Fact]
public void Test()
{
XmlSerializer serializer = new XmlSerializer(typeof(SiteDefinition));
using (FileStream stream = new FileStream("Data.xml", FileMode.Open))
{
var siteDefinition = (SiteDefinition)serializer.Deserialize(stream);
}
}
请注意,这个表达式是不正确的public List<MasterPage>? MasterPages
引用类型不能为空。以下是关于可空类型的更多信息
这里是关于XML序列化的附加信息