【问题标题】:C# adding data to arraysC# 向数组添加数据
【发布时间】:2011-12-06 15:08:51
【问题描述】:

我有这个代码:

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>
     */
}

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

每个&lt;account ID="test"&gt;&lt;/account&gt; 都是它自己的Account

【问题讨论】:

  • 如果您的 Account 类实际上与 XML 文档匹配,您可以尝试反序列化它。否则使用XmlReaderXDocument
  • 我已经完成了 Xml 的读取,我只需要让函数返回每个帐户。

标签: c# xml arrays collections


【解决方案1】:

考虑使用正确的 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; }
}

Account 类:

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

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

    // ... and so on
}

【讨论】:

    【解决方案2】:

    你可以做清单:

    var result = new List<Account>
    

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

    result.Add(account);
    

    最后归还:

    return result.ToArray();
    

    【讨论】:

    • 我不需要有关 XML 的帮助。我只需要有关集合的帮助。
    猜你喜欢
    • 2010-09-17
    • 2013-06-13
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 2020-03-28
    • 1970-01-01
    相关资源
    最近更新 更多