【发布时间】:2012-09-06 04:59:39
【问题描述】:
程序读取每个 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,如果你想确保使用正确的 XML,那么 XML Schema 可能是一个更好的选择
标签: c# xml linq-to-xml