更新时间:2023-08-19 22:31:34
看这一点:
var files = section.Elements("Files");
var fileList = new List<string>();
foreach (XElement area in files)
{
fileList.Add(area.Element("File").Value);
}
您正在遍历每个文件
元素,然后找出其中的第一个文件
元素。只有一个文件
元素 - 你必须遍历内的文件
元素
You're iterating over each Files
element, and then finding the first File
element within it. There's only one Files
element - you need to be iterating over the File
elements within that.
但是,也有绝对这样做的更好的方法。例如:
However, there are definitely better ways of doing this. For example:
var doc = XDocument.Load(Path.Combine(configPath, Resource.PBRuntimes));
var fileList = (from runtime in doc.Root.Elements("PowerBuilderRunTime")
where (int) runtime.Element("Version") == pbVersion
from file in runtime.Element("Files").Elements("File")
select file.Value)
.ToList();
请注意,如果有多的匹配 PowerBuilderRunTime
元素,将创建的所有的中的文件列表所有的那些元素。这可能不是你想要的。例如,您可能希望:
Note that if there are multiple matching PowerBuilderRunTime
elements, that will create a list with all the files of all those elements. That may not be what you want. For example, you might want:
var doc = XDocument.Load(Path.Combine(configPath, Resource.PBRuntimes));
var runtime = doc.Root
.Elements("PowerBuilderRunTime")
.Where(r => (int) r.Element("Version") == pbVersion)
.Single();
var fileList = runtime.Element("Files")
.Elements("File")
.Select(x => x.Value)
.ToList();
这将验证有完全的一个的匹配运行。
That will validate that there's exactly one matching runtime.