2013-02-19 45 views
6

我有xml文件,我需要根据新的客户端要求更新每一次。 由于xml文件的手动更新,大部分时间xml并不合适。 我想写一个程序(网页/窗口)提供适当的验证。 并基于来自ui的输入我将创建xml文件。下面是 是我的示例xml文件。基于我的c#类生成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> 

任何人都可以帮助我什么将是最好的方法呢?

+1

你在说什么样的验证? – 2013-02-19 08:52:58

+0

喜欢邮政编码字段的正则表达式 – Prashant 2013-02-19 08:55:54

+0

@Prashant对于xml标签是否小写很重要? – 2013-02-19 09:00:59

回答

11

创建下列类来保存数据,并对其进行验证:

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 { } 

和序列化的社区类的该实例为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); 

我觉得有点谷歌搜索将帮助您了解如何从文件反序列化社区对象。

+0

xml中的xml标签与cs文件中的相同。我如何可以使我的原始XML文件中的小案例。 – Prashant 2013-02-19 09:26:12

+0

感谢您的快速解答。 – Prashant 2013-02-19 09:27:29

+1

@Prashant使用'XmlElement'属性。像这样'[XmlElement(“name”)] public string Name {get;组; }'也需要社区类的'XmlRoot'属性。 – 2013-02-19 09:29:38