<?xml version="1.0" encoding="utf-8" ?>
<root>
<fileUploadSpecification>
<DirectoryPath>C:\watchFolder</DirectoryPath>
<Region>us-west-2</Region>
<UploadBucket>configurationtestbucket</UploadBucket>
<FileType>
<type>*.txt</type>
<type>*.OpticomCfg</type>
</FileType>
</fileUploadSpecification>
<fileUploadSpecification>
<DirectoryPath>C:\watchFolder</DirectoryPath>
<Region>us-west-2</Region>
<UploadBucket>loguploadbucket</UploadBucket>
<FileType>
<type>*.Xml</type>
<type>*.Json</type>
</FileType>
</fileUploadSpecification>
</root>
這是我需要解析的XML文件中添加多個元素的列表,我想fileUploadSpecification的每個實例,這樣我就可以把每一組的細節到一個列表,我覺得有些類型的for循環將是合適的,我循環並添加第一組上傳細節,然後循環並添加第二組。這是我目前擁有的,但它永遠不會到達第二個fileUploadSpecification元素,它只是再次返回相同的一個。 這個想法是創造每一套fileUploadSpecification元素的新SettingsData,無論是上述兩個等所示,或10C#中使用的XDocument
public interface ISettingsEngine
{
IEnumerable<SettingsData> GetSettings();
}
public class SettingsEngine : ISettingsEngine
{
public IEnumerable<SettingsData> GetSettings()
{
List<SettingsData> dataList = new List<SettingsData>();
try
{
var xDoc = XDocument.Load("File1.xml");
var instancesToParse = xDoc.Root.Elements().Count();
var fileCount = xDoc.Root.Elements("FileType").Count();
for (int x = 0; x < instancesToParse; x++)
{
var newSettingsData = new SettingsData();
newSettingsData.UploadBucket = xDoc.Root.Element("fileUploadSpecification").Element("UploadBucket").Value;
newSettingsData.Region = xDoc.Root.Element("fileUploadSpecification").Element("Region").Value;
newSettingsData.DirectoryPath = xDoc.Root.Element("fileUploadSpecification").Element("DirectoryPath").Value;
var query = xDoc.Root.Descendants("FileType").Elements("type");
foreach (XElement e in query)
{
newSettingsData.FileType.Add(e.Value);
}
dataList.Add(newSettingsData);
}
return dataList;
}
catch(Exception)
{
return dataList;
}
}
}
public class SettingsData
{
public List<string> FileType { get; set; }
public string DirectoryPath { get; set; }
public string Region { get; set; }
public string UploadBucket { get; set; }
public SettingsData()
{
FileType = new List<string>();
}
}
您認爲'xDoc.Root.Element(「fileUploadSpecification」)。Element(「UploadBucket」)。Value是什麼?您在閱讀文檔時發現了什麼? –
它獲取分配給該元素的文字值嗎?我想我明白,因爲它表明值是「配置測試桶」,這是我所期望的。我不明白的是,如何循環第二次,返回「UploadBucket」 - >「loguploadbucket」的第二個值 – John
我知道你不明白它做了什麼,我希望你也知道。我希望你知道,如果一種方法返回的結果完全不符合你期望的*,那麼你幾乎肯定不明白該方法的作用。在這一點上你不必向我保證。請閱讀文檔。 –