我有以下代码。
XElement opCoOptOff = doc.Descendants(ns + "OpCoOptOff").FirstOrDefault();
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;现在,如果我返回的元素为null,那么由于XElement为null,我将获得一个NullReferenceException。因此,我将其更改为以下内容。
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;
if(opCoOptOff != null)
{
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;我希望有一种更优雅的方式来做到这一点,因为这种情况经常出现,我希望避免每次出现问题时都进行这种类型的检查。任何帮助都将不胜感激。
发布于 2011-01-16 17:34:33
您可以编写extension method并在任何地方使用它:
public static class XDocumentExtension
{
public static string GetSubElementValue(this XElement element, string item)
{
if(element != null && element.Value != null)
{
if (element.Element(item) != null)
{
return element.Element(item).Value;
}
}
return null;
}
public static XElement GetElement(this XElement element, string item)
{
if (element != null)
return element.Element(item);
return null;
}
public static XElement GetElement(this XDocument document, string item)
{
if (document != null)
return document.Descendants("item").FirstOrDefault();
return null;
}
}将其用作:
String opCo = opCoOptOff.Element(ns + "strOpCo").GetSubElementValue(ns + "strOpCo");你也可以为你的目的添加其他的扩展。
编辑:我已经更新了答案,但是如果你在我写你可以add other extensions for your purpose.之前仔细阅读它,我写这篇文章是因为我猜你可能想调用空对象元素,我不知道你的确切情况是什么,但我添加了一些代码来做更多的澄清,根据你的情况完成XDocumentExtension类,一个注释扩展方法可以在空对象上工作。
发布于 2011-03-26 02:42:35
实际上,您可以将XElement直接转换为字符串:http://msdn.microsoft.com/en-us/library/bb155263.aspx
所以
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;可能是
string opCo = (string) opCoOptOff.Element(ns + "strOpCo");https://stackoverflow.com/questions/4704628
复制相似问题