C# Linq到XML:防止NullReferenceExpection
我得到了一个包含可选元素的XML,这些元素有时存在,有时不存在(..)。现在,这些可选元素本身也可能包含可选元素:C# Linq到XML:防止NullReferenceExpection,c#,xml,linq,linq-to-xml,C#,Xml,Linq,Linq To Xml,我得到了一个包含可选元素的XML,这些元素有时存在,有时不存在(..)。现在,这些可选元素本身也可能包含可选元素: <show> ... <text> <description> desc </description> </text> ... </show> <show> <title>I'm a show without text</title&
<show>
...
<text>
<description> desc </description>
</text>
...
</show>
<show>
<title>I'm a show without text</title>
</show>
<show>
<text>
<subtitle>I have a text-node but no description-node in it.</subtitle>
</text>
</show>
这感觉不太理想。。我需要查询更多的节点。对于Linq to Xml,我会选择:
var description = (string)xdoc.XPathSelectElement("//show/text/description");
在访问元素的值
属性时,使用转换为字符串以避免NullReference异常。尝试使用(字符串)XElement
转换而不是XElement。值
属性:
description = (string)show.Element("text").Element("description");
它将处理null
s
description = (string)show.Element("text").Element("description");