2014-05-15 101 views
0

我正在嘗試製作一個XML解析器,它將類對象的塊讀入文件中,並且也應該能夠編輯它。如何讀取/寫入對象到XML?

的類結構如下

[Serializable] 
public class Service 
{ 
    public enum ServiceStatus { ACTIVE, INACTIVE, SUSPENDED }; 

    //Unique identifier for a service 
    string _Id; 
    public string Id 
    { get{ return _Id;} 
     set{ _Id = value;} 
    } 

    //Name of the service, for reference of the client 
    string _name; 
    public string Name 
    { 
     get { return _name; } 
     set { _name = value; } 
    } 

    //URI where the service is hosted 
    string _uri; 
    public string Uri 
    { 
     get { return _uri; } 
     set { _uri = value; } 
    } 

    //The state of the service 
    ServiceStatus _status; 
    public ServiceStatus Status 
    { 
     get { return _status;} 
     set { _status = value; } 
    } 

    //the categories contained in the service instance 

    public ICollection<Category> Categories; 

    //collection of users/clients who can access this service 
    public ICollection<Client> Clients; 


    public Service() 
    { 
     _Id = null; 
     _name = null; 
     _uri = null; 
     _status = ServiceStatus.ACTIVE; 
     Categories = new List<Category>(); 
     Clients = new List<Client>(); 
    } 
} 

Category類是如下

public class Category 
{ 
    //Unique identifier for a category 
    string _Id; 
    public string Id 
    { 
     get { return _Id; } 
     set { _Id = value; } 
    } 

    //Name of the category, for reference of the client 
    string _name; 
    public string Name 
    { 
     get { return _name; } 
     set { _name = value; } 
    } 

    //URI where the category is hosted 
    string _uri; 
    public string Uri 
    { 
     get { return _uri; } 
     set { _uri = value; } 
    } 

    //Collection of pulses in this category 

    public ICollection<Pulse> Pulses; 

    public Category() 
    { 
     _Id = null; 
     _name = null; 
     _uri = null; 
     Pulses = new List<Pulse>(); 
    } 
} 

脈衝類是一個類似的類只用ID和名稱。

在xml文件中讀取/寫入這些對象的最佳方法是什麼?該操作是閱讀沉重,我希望讀取的值儘可能訪問,可能作爲數組索引或作爲字典,但任何形式都很好。

請提出最簡單的方法。我被c#中的XML的類數量所淹沒。

+5

使用與'XmlSerializer'類組合的類和屬性裝飾器。要開始,我建議閱讀這篇文章:http://msdn.microsoft.com/en-us/library/vstudio/2baksw0z(v=vs.100).aspx –

回答

0

將它轉換爲DataSet並執行您的操作怎麼樣? XmlTextReader.ReadXml(reader);

+0

我嘗試了一些東西..但被搞砸了。如果你能詳細解釋一下,那將是非常好的。 –

0

DataSet ds = new DataSet(); ds.ReadXml(fileNamePath);

這會將所有的XML轉換爲DataSet。將XML轉換爲DataSet後,您可以執行任何您想要執行的操作。