开发者

Refactor reading elements in an XML file - C#

开发者 https://www.devze.com 2023-03-02 00:07 出处:网络
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\").

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

精彩评论

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

关注公众号