0

我在需要使用 XMLText Reader 阅读的网站上托管了一个 XML 文件。在阅读时,我需要将阅读 XML 文档中的项目添加到类列表中。我不确定我应该通过哪些参数以及 foreach 部分。

transList 是我的列表,Transaction 是我的课程。它们已在顶部全局定义,以供 XML Serializer 将来用于写入我已经编写的 XML 文件。

具有多个事务的 XML 文件

<portfolio>
<transaction>
<ticker>GOOG</ticker>
<action>buy</action>
<date>20071116</date>
<shares>44</shares>
</transaction>


public class Transaction
{
    public string ticker { get; set; }
    public string action { get; set; }
    public string date { get; set; }
    public int numShares { get; set; }
    public double price { get; set; }
}

List<Transaction> transList = new List<Transaction>();


void readPortfolio(string filename)
    {
        XmlTextReader reader = new XmlTextReader(filename);
        reader.WhitespaceHandling = WhitespaceHandling.None;

        foreach(var transaction in reader) //for each reader node equal to “transaction” do:
         {
                TransList.add(Transaction tr = new Transaction(ticker, action, date, number of shares))

         }
4

3 回答 3

1

尝试这个:

public class Transaction
{
    public string Ticker { get; set; }
    public string Action { get; set; }
    public string Date { get; set; }
    public int NumShares { get; set; }
    public double Price { get; set; }
}

void ReadPortfolio(string filename)
{
    if (File.Exists(filename))
    {
        var transList = new List<Transaction>();

        foreach (XElement transaction in XDocument.Load(filename).Descendants("transaction"))
        {
            XElement ticker = transaction.Element("ticker");
            XElement action = transaction.Element("action");
            XElement date = transaction.Element("date");
            XElement shares = transaction.Element("shares");
            XElement price = transaction.Element("price");

            transList.Add(new Transaction
                {
                    Ticker = ticker != null ? ticker.Value : string.Empty,
                    Action = action != null ? action.Value : string.Empty,
                    Date = date != null ? date.Value : string.Empty,
                    NumShares = shares != null ? int.Parse(shares.Value) : default(int),
                    Price = price != null ? double.Parse(price.Value) : default(double)
                });
        }
    }
}

此方法处理可能缺少元素的情况,并且我已经稍微重写了您的代码以更符合惯例。它还检查文件是否存在。

这看起来像一个金融应用程序,所以我还应该指出,你最好使用decimal而不是double. decimal由于double.

于 2013-02-18T18:36:30.183 回答
0

这是使用 XDocument 执行此操作的方法...只需取消注释带有文件名的行(并注释解析常量的行!)并传入文件名。

class Program
{
    static void Main(string[] args)
    {
        var test = new AnotherXmlTest();
        test.readPortfolio("filename");

        //Put a break on this line and instect object 'test'
        Console.ReadLine();
    }
}

public class AnotherXmlTest
{
    public const string xml = @"<portfolio><transaction><ticker>GOOG</ticker><action>buy</action><date>20071116</date><shares>44</shares></transaction></portfolio>";


    public class Transaction
    {
        public string ticker { get; set; }
        public string action { get; set; }
        public string date { get; set; }
        public int numShares { get; set; }
        public double price { get; set; }
    }

    List<Transaction> transList = new List<Transaction>();


    public void readPortfolio(string filename)
    {
        //Use this instead!
        //XmlTextReader reader = new XmlTextReader(filename);
        //XDocument xDoc = XDocument.Load(reader);
        XDocument xDoc = XDocument.Parse(xml);

        transList.AddRange(from transaction in xDoc.Descendants("transaction")
                           select new Transaction
                           {
                               ticker = transaction.Element("ticker").Value,
                               action = transaction.Element("action").Value,
                               date = transaction.Element("date").Value,
                               numShares = Convert.ToInt32(transaction.Element("shares").Value)
                               // No price?? 
                           });


    }
}
于 2013-02-18T18:24:50.273 回答
0

如果你想变得漂亮,我提供的另一种方法是使用 LINQ:

public class Transaction
{
    public string Ticker { get; set; }
    public string Action { get; set; }
    public string Date { get; set; }
    public int NumShares { get; set; }
    public double Price { get; set; }
}

void ReadPortfolio(string filename)
{
    if (File.Exists(filename))
    {
        var transList = new List<Transaction>();
        transList.AddRange(from transaction in XDocument.Load(filename).Descendants("transaction")
                           let ticker = transaction.Element("ticker")
                           let action = transaction.Element("action")
                           let date = transaction.Element("date")
                           let shares = transaction.Element("shares")
                           let price = transaction.Element("price")
                           select new Transaction
                               {
                                   Ticker = ticker != null ? ticker.Value : string.Empty,
                                   Action = action != null ? action.Value : string.Empty,
                                   Date = date != null ? date.Value : string.Empty,
                                   NumShares = shares != null ? int.Parse(shares.Value) : default(int),
                                   Price = price != null ? double.Parse(price.Value) : default(double)
                               });
    }
}
于 2013-02-18T18:45:02.947 回答