c# – 访问可能存在或不存在的子元素时避免对象空引用异常
发布时间:2020-12-15 19:55:52 所属栏目:百科 来源:网络整理
导读:我有: 包含一些元素的 XML. 可以在此 XML中定义的子元素,也可以不在此XML中定义. 需要在子元素存在时提取子元素的值. 如何在不抛出对象引用错误的情况下获取值? 例如: string sampleXML = "RootTag1tag1value/Tag1/Root"; //Pass in Tag2 and the code wo
我有:
包含一些元素的 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; 解决方法
首先,你应该检查文档是否为null,记住你正在访问.Value,这将抛出一个空引用异常,所以在你申请之前.value做一个测试:
if (sampleEl != null) //now apply .value 或者三元: string tag2 = sampleEl.Element("Tag2") != null ? sampleEL.Element("Tag2").Value : String.Empty 然后你的代码变成: 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 = sampleEl.Element("Tag1") != null ? sampleEl.Element("Tag1").Value : String.Empty; //NullReferenceException: //Object reference not set to an instance of an object. string tag2 = sampleEl.Element("Tag2") != null ? sampleEL.Element("Tag2").Value : String.Empty (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |