【问题标题】:Check if root element exists检查根元素是否存在
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

  • null 有效!谢谢!我现在真的看起来很愚蠢.. :) 只是问,在 .Elements() 中是否还有其他更直接的方法,例如 .Any()?
  • 不,当您只是检查元素是否存在时,空检查是最好的方法。
【解决方案2】:

或者你可以这样做:)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    • 2010-09-11
    • 2021-05-04
    相关资源
    最近更新 更多