访问可能存在或不存在的子元素时,避免使用对象空引用异常

Los*_*der 3 .net c# exception-handling linq-to-xml nullreferenceexception

我有:带有一些元素的XML.可以在此XML中定义的子元素,也可以不在此XML中定义.需要在子元素存在时提取子元素的值.

如何在不抛出对象引用错误的情况下获取值?

例如:

 string sampleXML = "<Root><Tag1>tag1value</Tag1></Root>"; 

//Pass in <Tag2> and the code works: 
//string sampleXML = "<Root><Tag1>tag1value</Tag1><Tag2>tag2Value</Tag2></Root>";    
 XDocument sampleDoc = XDocument.Parse(sampleXML);

//Below code is in another method, the 'sampleDoc' is passed in. I am hoping to change only this code
XElement sampleEl = sampleDoc.Root; 
string tag1 = String.IsNullOrEmpty(sampleEl.Element("Tag1").Value) ? "" : sampleEl.Element("Tag1").Value;

//NullReferenceException:
//Object reference not set to an instance of an object.
string tag2 = String.IsNullOrEmpty(sampleEl.Element("Tag2").Value) ? "" : sampleEl.Element("Tag2").Value;
Run Code Online (Sandbox Code Playgroud)

Bro*_*ass 10

您可以使用null-coalescing-operator作为快捷方式:

 string tag1= (string)sampleEl.Element("Tag1") ?? string.Empty;
Run Code Online (Sandbox Code Playgroud)

这也使用LINQ to XML允许转换操作获取元素的值(在这种情况下转换为字符串),但null如果元素不存在则返回.