检查根元素是否存在

时间:2012-09-06 04:59:39

标签: c# xml linq-to-xml

程序读取每个XML文件的“File”元素的值并对其执行某些操作。我需要一个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();
        }

2 个答案:

答案 0 :(得分:2)

这里不会进行简单的空检查吗?

    var configuration = xdoc.Element("CONFIGURATION");

    if (configuration != null)
    {
            // code...
    }

答案 1 :(得分:1)

或者你可以这样做:)

if (xdoc.Elements("CONFIGURATION").Any())
{
}