【问题标题】:how to check xDocument is null or Empty in c#如何在 c# 中检查 xDocument 是否为空或为空
【发布时间】:2016-10-17 20:04:59
【问题描述】:

我要处理不包含任何数据的空文件 运行下面的代码后,它会给出错误,例如缺少根元素。

如何检查xDoc 是否为空或为空?

string path = @"E:\Test.xml";
XDocument xDoc = XDocument.Load(path);

【问题讨论】:

  • 路径已存在但文件为空,我可以使用 try catch 但需要其他方法来检查特定 XDocument 是否为空或为空
  • 不明白为什么 try catch 块没有回答你的问题,你能解释一下你想要什么结果吗?
  • 我只是想避免这个错误,对于字符串,我们可以像 string.IsNullOrEmpty() 这样简单地检查为什么我们不能检查任何 XmlDoxument 或 XDocument
  • @yashfale 因为这不是字符串...

标签: c# xml linq-to-xml


【解决方案1】:

XDocument.Load 需要一个有效的 XML 文件。否则会抛出异常。您可以在调用 XDocument.Load 之前检查文件是否存在或为空,例如通过

if (new System.IO.FileInfo(path).Length > 0)
{
   ...
}

或者你可以捕获异常。

string path = @"E:\Test.xml";
try
{
    XDocument xDoc = XDocument.Load(path);
} catch(Exception) {
   // some problem
}

如果将此代码放入静态函数中,则代码将更具可读性。

 var xDoc = MyXDocument.Load(path);
 if (xDoc != null)
 { .... 
 }

public class MyXDocument {
    public static XDocument Load(string path) {
        try
        {
             XDocument xDoc = XDocument.Load(path);
             return xDoc;
        } catch(Exception) {
            return null;
        }
    }
}

【讨论】:

  • 我可以这样处理,但需要一些其他方法来检查 XDocument 是否为空或为空
  • @yashfale - 您能否详细说明您的问题,为什么这些检查不符合您的要求?如果是样式问题,您可以编写像 MyXDocument.Load() 这样的静态辅助方法,如果加载期间发生错误,则返回 null。
  • 明白了! ,我们必须使用 try catch 块。没有其他方法可以检查 XDocument 的 null 或空。谢谢。
猜你喜欢
  • 2012-03-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2012-11-24
  • 2013-06-19
  • 2013-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多