简体   繁体   中英

If Element does not exist

I have around a dozen solutions to this, but none seem to fit what I am trying to do. The XML file has elements that may not be in the file each time it is posted.

The trick is, the query is dependent upon a question value to get the answer value. Here is the code:

string otherphone = (
    from e in contact.Descendants("DataElement")
    where e.Element("QuestionName").Value == "other_phone"
    select (string)e.Element("Answer").Value
).FirstOrDefault();
otherphone = (!String.IsNullOrEmpty(otherphone)) ? otherphone.Replace("'", "''") : null;

Under the "contact" collection, here are many elements named "DataElement", each with its own "QuestionName" and "Answer" elements, so I query to find the one where the element's QuestionName value is "other_phone", then I get the Answer value. Of course I will need to do this for each value I am seeking.

How can I code this to ignore the DataElement containing QuestionName with value of "other_phone" if it doesn't exist?

You can use Any method to check whether or not the elements exists :

if(contact.Descendants("DataElement")
     .Any(e => (string)e.Element("QuestionName") == "other_phone"))
{
   var otherPhone =  (string)contact
                   .Descendants("DataElement")
                   .First(e => (string)e.Element("QuestionName") == "other_phone")
                   .Element("Answer");
}

Also, don't use Value property if you are using explicit cast.The point of explicit cast is avoid the possible exception if the element wasn't found.If you use both then before the cast, accessing the Value property will throw the exception.

Alternatively, you can also just use the FirstOrDefault method without Any , and perform a null-check:

var element =  contact
              .Descendants("DataElement")
              .FirstOrDefault(e => (string)e.Element("QuestionName") == "other_phone");

if(element != null)
{
    var otherPhone = (string)element.Element("Answer");
}

So you want to know if other_phone exists or not?

XElement otherPhone = contact.Descendants("QuestionName")
    .FirstOrDefault(qn => ((string)qn) == "other_phone");

if (otherPhone == null)
{
   // No question with "other_phone"
}
else
{
    string answer = (string)otherPhone.Parent.Element("Answer");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM