
包含一些元素的 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 codeXElement 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 总结 以上是内存溢出为你收集整理的c# – 访问可能存在或不存在的子元素时避免对象空引用异常全部内容,希望文章能够帮你解决c# – 访问可能存在或不存在的子元素时避免对象空引用异常所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)