2013-02-19 10 views
6

私は新しいクライアント要件ごとに毎回更新する必要があるxmlファイルを持っています。 xmlファイルの手動更新のため、ほとんどの時間xmlが適切ではありません。 私は、適切な検証が提供されるプログラム(web/windows)を書くことを考えています。 と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

あなたはどんな種類のバリデーションをしていますか? –

+0

ポストコードフィールドの正規表現 – Prashant

+0

のように@Prashantは、xmlタグが小文字であることは重要ですか? –

答えて

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

+0

あなたの迅速な解決に感謝します。 – Prashant

+1

@Prashantは 'XmlElement'属性を使います。このように '[XmlElement(" name ")] public string Name {get;セット; } 'コミュニティクラスには' XmlRoot'属性が必要です。 –

関連する問題