if exists XML Element

Mansoor Mohammed 61 Reputation points
2021-03-05T21:46:30.123+00:00

from the below code
How do i find, if there EXISTS an xmlElemenent MiddleName(i am not asking for value) before i evaluate it
something like if exists(MiddleName) then.....
Sometimes in my xml the attribute(not the value) might not exists

public static string ProcessXMLdata(XElement xml)
{
try {

string processResult;
XNamespace ns="http://schemas.datacontract.org/2004/07/BondData.Shared.DataModels.Peoplehouse";

if (xml.Element(ns + "FirstName").Value == null ||
xml.Element(ns + "LastName").Value == null ||
xml.Element(ns + "MiddleName").Value == null ||
xml.Element(ns + "ApplicantAddress").Value == null ||

Developer technologies C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2021-03-06T06:44:47.993+00:00

    According to documentation, if element does not exists, then xml.Element(ns + "MiddleName") will be null. Therefore, you can use a condition like ‘xml.Element(ns + "MiddleName") == null’.

    If you want to check if the element does not exists or the value is null or empty, try

    xml.Element(ns + "MiddleName")?.Value == null

    or

    string.IsNullOrWhitespace(xml.Element(ns + "MiddleName")?.Value)

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.