trx
trx

Reputation: 2157

Handling nodes that does exists while parsing

I have the XML response of API that looks like below

<lab:lab uri="https://bh03.org/api/lb/3" xmlns:udf="http://ge.com/ri/userdefined" xmlns:ri="http://ge.com/ri" xmlns:lab="http://ge.com/ri/lab">
    <name>GTech</name>
    <udf:field type="String" name="Account ID">gt</udf:field>
</lab:lab>

I want to get the value 'gt' of Account ID from the XML so I am using XDocument Parse and using the below code

XDocument new_doc = XDocument.Parse(responseString_LabURL);
XNamespace ns = "http://ge.com/ri/userdefined";
string accountID = new_doc.Descendants(ns + "field").FirstOrDefault(field => field.Attribute("name").Value.Equals("Account ID")).Value;

But sometimes there will be no <udf:field type="String" name="Account ID">gt</udf:field> in the XML and might look like the below

<lab:lab uri="https://bh03.org/api/v2/labs/1302" xmlns:udf="http://ge.com/ri/userdefined" xmlns:ri="http://ge.com/ri" xmlns:lab="http://ge.com/ri/lab">
    <name>lsd</name>
</lab:lab>

How to handle when there is no field.

Upvotes: 1

Views: 24

Answers (1)

Daniel
Daniel

Reputation: 9829

I would start testing if the element <udf:field></udf:field> exists. Like this:

string accountID;
XDocument new_doc = XDocument.Parse(responseString_LabURL);
XNamespace ns = "http://ge.com/ri/userdefined";

if (new_doc.Descendants(ns + "field").Any())
{
    accountID = new_doc.Descendants(ns + "field").FirstOrDefault(field => field.Attribute("name").Value.Equals("Account ID")).Value;
}
else
{
    accountID = null; // or whatever
} 

Shorthand for the above code is:

accountID = new_doc.Descendants(ns + "field").Any() ? new_doc.Descendants(ns + "field").FirstOrDefault(field => field.Attribute("name").Value.Equals("Account ID")).Value : null;

Upvotes: 1

Related Questions