LINQ to XML: handle nodes that don't exist?

It might be a simple fix (well, probably it is), but for some reason I just can't figure it out.

So I have an xml that looks something like this:

XElement xml = XElement.Parse (
@"<Alphabet>
     <a name="A" />
     <b name="B" />
     <d name="D" />
     <e name="E" />
</Alphabet>");

So, in my code, I refer to node, which may or may not exist there, for example:

var name = (from b in xml.Descendants("c")
            select b.Attribute("name")).FirstOrDefault().Value;

But when it does not exist, instead of returning null or "", it throws a NullReferenceException: Object does not refer to an instance of the object.

What is the best way to check and see if node exists in my linq query? Or do I need to check if it exists in another way?

+3
source share
4 answers

, - :

var nameAttribute = xml.Descendants("c").Select(b => b.Attribute("name"))
                                        .FirstOrDefault();
if (nameAttribute != null)
{
    string name = nameAttribute.Value;
}
else
{
    // Whatever...
}

( , - .)

: "c", "name", "c". ?

+5

.

public static string GetAttributeValue(this XElement element, string attributeName)
{
    XAttribute attribute = element.Attribute(attributeName);
    return attribute != null ? attribute.Value : string.Empty;
}

public static string GetElementValue(this XElement element)
{
    return element != null ? element.Value : string.Empty;
}

public static string GetElementValue(this XElement element, string elementName)
{
    XElement child = element.Element(elementName);
    return child != null ? child.Value : string.Empty;
}
+4

FirstOrDefaultreturns nullor XAttribute, which you can pass in stringto get the value:

var name = (string)((from b in xml.Descendants("c")
                     select b.Attribute("name")).FirstOrDefault());

or

var name = (string)xml.Descendants("c")
                      .Select(b => b.Attribute("name"))
                      .FirstOrDefault();
+1
source

You can do something like this:

var name = (from b in xml.Descendants("c")
            select b.Attribute("name").Value).FirstOrDefault();

or if you really need an element:

var name = (from b in xml.Descendants("c")
            select b.Attribute("name")).FirstOrDefault();

if (name != null)
{
    // your logic ...
}
0
source

Source: https://habr.com/ru/post/1724778/


All Articles