Pra*_*ant 9 c# xml xml-serialization c#-4.0
我有xml文件,我需要根据新的客户端要求每次更新.大多数情况下,由于手动更新xml文件,xml不正确.我正在考虑编写一个程序(web/windows),提供适当的验证.并根据ui的输入,我将创建xml文件.下面是我的示例xml文件.
<community>
<author>xxx xxx</author>
<communityid>000</communityid>
<name>name of the community</name>
<addresses>
<registeredaddress>
<addressline1>xxx</addressline1>
<addressline2>xxx</addressline2>
<addressline3>xxx</addressline3>
<city>xxx</city>
<county>xx</county>
<postcode>0000-000</postcode>
<country>xxx</country>
</registeredaddress>
<tradingaddress>
<addressline1>xxx</addressline1>
<addressline2>xxx</addressline2>
<addressline3>xxx</addressline3>
<city>xxx</city>
<county>xx</county>
<postcode>0000-000</postcode>
<country>xxx</country>
</tradingaddress>
</addresses>
<community>
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助我什么是最好的方法?
Ser*_*kiy 16
创建以下类来保存数据并对其进行验证:
public class Community
{
public string Author { get; set; }
public int CommunityId { get; set; }
public string Name { get; set; }
[XmlArray]
[XmlArrayItem(typeof(RegisteredAddress))]
[XmlArrayItem(typeof(TradingAddress))]
public List<Address> Addresses { get; set; }
}
public class Address
{
private string _postCode;
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string PostCode
{
get { return _postCode; }
set {
// validate post code e.g. with RegEx
_postCode = value;
}
}
}
public class RegisteredAddress : Address { }
public class TradingAddress : Address { }
Run Code Online (Sandbox Code Playgroud)
并将社区类的实例序列化为xml:
Community community = new Community {
Author = "xxx xxx",
CommunityId = 0,
Name = "name of community",
Addresses = new List<Address> {
new RegisteredAddress {
AddressLine1 = "xxx",
AddressLine2 = "xxx",
AddressLine3 = "xxx",
City = "xx",
Country = "xxxx",
PostCode = "0000-00"
},
new TradingAddress {
AddressLine1 = "zz",
AddressLine2 = "xxx"
}
}
};
XmlSerializer serializer = new XmlSerializer(typeof(Community));
serializer.Serialize(File.Create("file.xml"), community);
Run Code Online (Sandbox Code Playgroud)
我认为有点谷歌搜索将帮助您了解如何从文件反序列化社区对象.