C#向数组添加数据

时间:2011-12-06 15:08:52

标签: c# xml arrays collections

我有这段代码:

public static Account[] LoadXml(string fileName) {
     Account ths = new Account();
     // load xml data
     // put data into properties/variables
     // the xml is in a structure like this:
     /*
     <accounts> 
        <account ID="test account">
         <!-- account variables here -->
        </account>
        <account ID="another test account">
         <!-- account variables here -->
        </account>
     </accounts>
     */
}

我如何返回包含这些帐户的数组或集合?

每个<account ID="test"></account>都是自己的Account

2 个答案:

答案 0 :(得分:6)

考虑使用正确的xml序列化而不是自己编写。 .NET框架可以为您处理所有问题,包括数组,集合或列表。

您的代码应该像这样简单:

using (var stream = File.OpenRead(filename)) {
    var serializer = new XmlSerializer(typeof(AccountsDocument));
    var doc = (AccountsDocument)serializer.Deserialize(stream);
    return doc.Accounts;
}

AccountsDocument类:

[XmlRoot("accounts")]
public class AccountsDocument {
    [XmlElement("account")]
    public Account[] Accounts { get; set; }
}

帐户类:

public class Account {
    [XmlAttribute("ID")]
    public string Id { get; set; }

    [XmlElement("stuff")]
    public StuffType Stuff { get; set; }

    // ... and so on
}

答案 1 :(得分:1)

你可以做清单:

var result = new List<Account>

然后将项目添加到列表中:

result.Add(account);

最后归还:

return result.ToArray();