开发者

Refactor reading elements in an XML file - C#

Can I refactor the following piece of code reading elements in an XML file:

if (!(xmlDoc.Element("Element1").Element("Element2").Element("Element3").Element("Element4").Element("Element5").Element("Element6") 开发者_运维知识库== null))
{

}


Try use XPath expression for find element what you want, this code who you submited can easly throw unexpected NullReferenceException who probably you don't want catch.

Something like this:

if (xPath.evaluate("count(/Element1/Element2/Element3/Element4)", xmlDoc) > 0)
{
}

PS. Why you negating expression of == null? Better readable and maintainable is != null without negation and trailing () in your boolean expression.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜