該程序讀取每個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();
}
什麼!我做錯了選票嗎? – Blackator
我同意,爲什麼這個問題被低估?,除了那個@Blackator,如果你想確保你使用正確的XML,那麼XML Schema可能是一個更好的選擇 – Habib