[英]NullReferenceException when trying to write in app.config
[英]NullReferenceException was unhandled error when trying to retrieve config attributes
public string GetLogName(string config)
{
XDocument xDoc = XDocument.Load(config);
XElement[] elements = xDoc.Descendants("listeners").Descendants("add").ToArray();
foreach (var element in elements)
{
if (element.Attribute("fileName").Value != null)
{
string filename = element.Attribute("fileName").Value;
int location = filename.IndexOf("%");
Console.WriteLine("string to return: " + filename.Substring(0, location));
return filename.Substring(0, location);
}
}
}
我试图从elements数组中的每个元素检索“ fileName”属性,但是在某些情况下,“ fileName”属性不存在并且失败并出现以下错误:未处理NullReferenceException。 你调用的对象是空的。
在我的情况下,有两个“添加”节点不具有“ fileName”属性,但是第三个添加节点具有它。
如何跳过不具有“ fileName”属性的条目,或者您可以推荐一种更好的方法来检索此属性?
您只需更改以下行就可以执行此操作:
if (element.Attribute("fileName").Value != null)
至:
if (element.Attribute("fileName") != null)
将您的if语句更改为此:
if (element.Attribute("fileName") != null)
一种方法是在处理列表之前将其过滤掉:
XElement[] elements = xDoc.Descendants("listeners")
.Descendants("add")
.Where (d => d.Attribute("filename") != null )
.ToArray();
---恕我直言,这就是我使用linq和regex重写方法的方式---
var elements =
XDocument.Load(config);
.Descendants("listeners")
.Descendants("add")
.Where (node => node.Attribute("filename") != null )
.ToList();
return elements.Any() ? elements.Select (node => node.Attribute("filename").Value )
.Select (attrValue => Regex.Match(attrValue, "([^%]+)").Groups[1].Value)
.First ()
: string.Empty;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.