该程序读取每个 XML 文件的“文件”元素的值并对其进行处理。我需要一个 if 语句首先检查根元素是否为“CONFIGURATION”(这是检查程序正在读取的 XML 是否正确的方法)。我的问题是您不能将 .Any() 添加到 .Element,只能添加到 .Elements。而且我下面的 if 语句不起作用,我需要更改它。
请参阅 if 语句之前的注释。
我的代码:
static void queryData(string xmlFile)
{
var xdoc = XDocument.Load(xmlFile);
var configuration = xdoc.Element("CONFIGURATION");
//The code works except for the if statement that I added.
//The debug shows that configuration is null if no "CONFIGURATION" element is found,
//therefore it prompts a "NullReferenceException" error.
if (configuration == xdoc.Element("CONFIGURATION"))
{
string sizeMB = configuration.Element("SizeMB").Value;
string backupLocation = configuration.Element("BackupLocation").Value;
string[] files = null;
Console.WriteLine("XML: " + xmlFile);
if (configuration.Elements("Files").Any())
{
files = configuration.Element("Files").Elements("File").Select(c => c.Value).ToArray();
}
else if (configuration.Elements("Folder").Any())
{
files = configuration.Elements("Folder").Select(c => c.Value).ToArray();
}
StreamWriter sw = new StreamWriter(serviceStat, true);
sw.WriteLine("Working! XML File: " + xmlFile);
foreach (string file in files)
{
sw.WriteLine(file);
}
sw.Close();
}
else
{
StreamWriter sw = new StreamWriter(serviceStat, true);
sw.WriteLine("XML Configuration invalid: " + xmlFile);
sw.Close();
}