2013-02-18 122 views
1

我有一個名爲portfolio的xml文件,我將該位置作爲字符串傳遞。 從元素下的組合文件中讀取文件名列表。在xml文件中,我有一個叫做元素的元素,我需要讀取價格數據中的4個值並將其存儲到字符串列表中。我不知道我是否正確地做了這件事。我不知道我的參數應該用於foreach循環。將xml元素添加到來自XML閱讀器的列表

XML文件:

<priceData> 
    <file name="ibmx.xml"/> 
    <file name="msft.xml"/> 
    <file name="ulti.xml"/> 
    <file name="goog.xml"/> 
</priceData> 

這裏是我的功能爲C#

public static void readPortfolio(string filename) 
{ 
    XmlTextReader reader = new XmlTextReader(filename); 
    reader.Read(); 
    List<string> priceDataFile = new List <string>(); 
    foreach(var file in reader) //Don't know what the parameters should be. 
    { 
     priceDataFile.Add(reader.Value); //Not sure if I am passing what I want 
    } 
} 

回答

0

你可以做到這一點。以下內容會將每個屬性的文件名添加到列表中 將我的.XML文件的副本替換爲您的路徑位置。

XDocument document = XDocument.Load(@"C:\Sample_Xml\PriceData.xml"); 
List<string> priceDataFile = new List<string>(); 
var priceData = (from pd in document.Descendants("priceData") 
        select pd); 

foreach (XElement priceValue in priceData.Elements()) 
{ 
    priceDataFile.Add(priceValue.FirstAttribute.Value.ToString()); 
} 

這是你priseDataFile列出內容將是什麼樣子 在快速監視

[0] "ibmx.xml" 
[1] "msft.xml" 
[2] "ulti.xml" 
[3] "goog.xml" 
+0

你不需要'ToList()'這裏。 – abatishchev 2013-02-18 03:25:21

+0

我編輯了答案並測試了它的工作原理,謝謝abatishchev – MethodMan 2013-02-18 16:01:44

0

查看它使用的XDocument類是解決它。但是,如果你想使用XmlTextReader類的好方法,該代碼已被列爲如下。然後你會得到包含XML文件列表的結果。無論如何,name是您示例代碼中的一個屬性。所以你應該使用reader.GetAttribute(「name」)來獲得價值。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 

namespace XmlReaderTest 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      XmlTextReader reader = new XmlTextReader("../../Portfolio.xml"); 
      reader.WhitespaceHandling = WhitespaceHandling.None; 
      List<string> priceDataFile = new List<string>(); 
      while (reader.Read()) 
      { 
       if (reader.Name == "file") 
       { 
        priceDataFile.Add(reader.GetAttribute("name")); 
       } 
       else 
        continue; 
      } 

      reader.Close(); 

      foreach (string file in priceDataFile) 
      { 
       Console.WriteLine(file); 
      } 

      Console.ReadLine(); 
     } 
    } 
} 
+0

@DJ KRAZE我同意你的意見。如果Martin不需要使用XmlTextReader類,則XDocument類更好。 Linq將簡化您的代碼。 – Tonix 2013-02-18 02:58:41

0

使用LINQ到XML代替(.NET 3.0+):

XDocument doc = XDocument.Load(path); 
List<string> list = doc.Root 
         .Elements("file") 
         .Select(f => (string)f.Atribute("name")) 
         .ToList();