プログラムは、各XMLファイルの「ファイル」要素の値を読み取り、それに対して何かを実行します。ルート要素が「CONFIGURATION」であるかどうかを最初にチェックするifステートメントが必要です(これは、プログラムが読み取っている正しい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();
}