如何读取/写入xml对象?

时间:2014-05-15 14:27:59

标签: c# xml parsing

我正在尝试创建一个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和name。

在xml文件中读取/写入此类对象的最佳方法是什么。操作读取很重,我希望尽可能读取值,可以作为数组索引或字典,但任何形式都可以。

请建议最简单的方法。我对c#

中XML的类数量感到不知所措

2 个答案:

答案 0 :(得分:0)

如何将其转换为DataSet并执行操作? XmlTextReader.ReadXml(读取器);

答案 1 :(得分:0)

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

这会将您的所有XML转换为DataSet。将XML转换为DataSet后,您可以执行您想要执行的任何操作。