c# - Check for missing elements while using LINQ to XML -
i trying data xml. below code gets data xdocument , return list<t>
.
however, p.element("sponsor")
can null. how can check null values
var atclauselist = doc.descendants(clause_group_tag).descendants(at_clause_tag).select(p => new atclause() { clausenumber = (string)p.element("number"), sponsors = p.element("sponsor").elements(sponsor_tag).select(y => y.value) .tolist(), page = p.element("sponsor").element("aitem").element("amendtext").element("page").elementvaluenull(), line = p.element("sponsor").element("aitem").element("amendtext").element("line").elementvaluenull(), linetext = p.element("sponsor").element("aitem").element("amendtext").nodes().oftype<xtext>().firstordefault().xtextvaluenull(), italictext = p.element("sponsor").element("aitem").element("amendtext").element("italic").elementvaluenull(), paralist = p.element("sponsor").element("aitem").element("amendtext").elements("para").select(l => new para { paratext = (string)l, number = ((system.xml.linq.xelement)(l)).attributevaluenull("number"), quote = ((system.xml.linq.xelement)(l)).attributevaluenull("quote"), } ).tolist() }).tolist();
move code out of object initializer, , add logic it:
var atclauselist = new list<atclause>(); foreach(var item in doc.descendants(clause_group_tag).descendants(at_clause_tag)) { var atclause = new atclause(); atclause.clausenumber = (string)item.element("number"); var sponsor = item.element("sponsor"); if (sponsor != null) { atclause.sponsors = sponsor.elements(sponsor_tag).select(y => y.value).tolist(); atclause.page = sponsor.element("aitem").element("amendtext").element("page").elementvaluenull(); atclause.line = sponsor.element("aitem").element("amendtext").element("line").elementvaluenull(); atclause.linetext = sponsor.element("aitem").element("amendtext").nodes().oftype<xtext>().firstordefault().xtextvaluenull(); atclause.italictext = sponsor.element("aitem").element("amendtext").element("italic").elementvaluenull(); atclause.paralist = sponsor.element("aitem").element("amendtext").elements("para").select(l => new para { paratext = (string)l, number = ((system.xml.linq.xelement)(l)).attributevaluenull("number"), quote = ((system.xml.linq.xelement)(l)).attributevaluenull("quote"), }).tolist(); atclauselist.add(atclause); }
Comments
Post a Comment