I have a XML Like this:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<SampleResponse xmlns="http://tempuri.org/">
<SampleResult>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<NewDataSet xmlns="">
<Table diffgr:id="Table1" msdata:rowOrder="0">
<tag1>tag1 text</tag1>
<tag2>tag2 text</tag2>
</Table>
<Table diffgr:id="Table2" msdata:rowOrder="1">
<tag1>tag1 text</tag1>
<tag2>tag2 text</tag2>
</Table>
</NewDataSet>
</diffgr:diffgram>
</SampleResult>
</SampleResponse>
</soap:Body>
</soap:Envelope>
here i am parsing above XML Like Below:
// My parser Class
class ParseClass
{
public string tag1 { get; set; }
public string tag2 { get; set; }
}
My parsing Code is:
string XMLresponse = e.response;
var XResult = XElement.Parse(XMLresponse);
var result = XResult.Descendants("Table").Select(t => new ParseClass
{
tag1 = t.Descendants("tag1").First().Value,
tag2 = t.Descendants("tag2").First().Value,
});
foreach (var res in result1)
{
string str=res.tag1;
str=res.tag2;
}
I am able parse above XML successfully if all the tags are coming. But some times my response XML is missing tag called tag2, at that time i am not able to parse the XML and giving exception like “sequence contains no elements”.
Here my requirement is:
I have tried FirstOrDefault method in place of First method but no use.
if any tag is missing in XML then that variable should be Null for that Object(i.e: if tag2 is missing then res.tag2 should be null). How can i achieve this?
Instead of using
use
(And likewise for tag2.)
FirstOrDefault()will returnnullif the value isn’t present, and theXElementto string conversion will return null when asked to convert a null reference, or the text content otherwise.