C#向数组添加数据

tr0*_*ing -4 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>
     */
}
Run Code Online (Sandbox Code Playgroud)

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

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

And*_*lad 6

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

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

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

AccountsDocument类:

[XmlRoot("accounts")]
public class AccountsDocument {
    [XmlElement("account")]
    public Account[] Accounts { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

帐户类:

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

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

    // ... and so on
}
Run Code Online (Sandbox Code Playgroud)