2013-02-18 58 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();