从Xml文件读取并添加到字符串列表列表

时间:2013-02-18 03:01:56

标签: c# xml list xmlreader xmlnode

尝试从我的电脑上的XML文件中读取。该函数使用字符串值来传递静态函数。我想要每个事务,创建一个所谓的"节点"我猜。我想说的数组是因为我来自C ++ / Java背景。每个列表都有一个列表。交易清单,在每个交易中,我都有与该交易相对应的股票价值,操作值,日期值和股票价值。这就是我到目前为止所拥有的。

XML文件

<stocks>
<transaction>
<ticker>GOOG</ticker>
<action>buy</action>
<date>20071116</date>
<shares>44</shares>
</transaction>
<transaction>
<ticker>IBMX</ticker>
<action>buy</action>
<date>20080104</date>
<shares>350</shares>
</transaction>

C#代码

public static  void readXML(string filename)
    {
        XmlTextReader reader = new XmlTextReader(filename);
        List<List<string>> transList = new List<List<string>>();
        XmlNode node = 

        foreach(var transaction in reader())
        {
            transList.Add(new Transaction(node.get ticker,node.action,node.date,node.shares)

        }

1 个答案:

答案 0 :(得分:0)

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

    private List<Transaction> getTransactionsFromFile(string filename)
    {
        XmlDocument xDoc = new XmlDocument();
        xDoc.Load(filename);
        List<Transaction> tranList = new List<Transaction>();

        foreach (XmlNode x in xDoc)
        {
            if (x.Name == "stocks")
            {
                foreach (XmlNode y in x.ChildNodes)
                {
                    if (y.Name == "transaction")
                    {
                        Transaction tempTran = new Transaction();
                        foreach (XmlNode z in y.ChildNodes)
                        {
                            if (z.Name == "ticker")
                            {
                                tempTran.Ticker= z.InnerText;
                            }
                            if (z.Name == "action")
                            {
                                tempTran.Action= z.InnerText;
                            }
                            if (z.Name == "date")
                            {
                                tempTran.Date = z.InnerText;
                            }
                            if (z.Name == "shares")
                            {
                                tempTran.NumShares = int.Parse(z.InnerText);
                            }

                            if (z.Name == "PassOutputToChildSteps")
                        }
                        //add the constructed Transaction Object to the Transaction List...
                        tranList.Add(tempTran);
                    }
                }
            }
        }
        return tranList;
    }