从C#中的xml文件中获取重复节点的信息

时间:2013-10-10 06:41:09

标签: c# .net xml c#-4.0 c#-3.0

我有一个xml文件,如下所示:

<Root>
  <Folder1>
    <file>AAA</file>
    <file>BBB</file>
    <file>CCC</file> 
  </Folder1>
  <Folder2>
    <file>AAA</file>
    <file>BBB</file> 
    <file>CCC</file> 
  </Folder2>
</Root>

我需要所有父母的字符串列表, 我尝试使用

using (XmlTextReader reader = new XmlTextReader(pathFiles))              
{                    
   reader.ReadToFollowing("file");
   string files = reader.ReadElementContentAsString();
}

因此,“files”变量仅包含“AAA”,

reader.ReadElementContentAsString()不接受列表。

有没有办法将输出提取为{“AAA”,”BBB”,”CCC”, AAA”,”BBB”,”CCC”}

2 个答案:

答案 0 :(得分:4)

XDocument doc=XDocument.Load(xmlPath);
List<string> values=doc.Descendants("file")
                       .Select(x=>x.Value)
                       .ToList();

答案 1 :(得分:2)

试试这个

XDocument xdoc = XDocument.Parse(xml);
var filesArray = xdoc.Elements()
    .First()
    .Descendants()
    .Where(x => x.Name == "file")
    .Select(x => x.Value)
    .ToArray();
相关问题