Missing nodes nullify null xml xml exceptions

I get a null exception because MYTAG1 does not exist. I understand that this is because Element ("MYTAG1") is null and the call to "Elements" ("MYTAG2") does not work on it.

How can I handle this to prevent a crash?

     var myItems = from myNode in Nodes.Element("MYTAG1").Elements("MYTAG2")
                           select new EPTableItem
                           {
                           //    Assign stuff here                            
                           };
+3
source share
5 answers

I can't think of a smart way to include the statement ifin the C # request syntax, so I will offer the following solution that checks the required node before executing the request.

var myItems;
XElement myTag1 = myNode.Element("MYTAG1");

if (myTag1 != null)
{
    myItems = from myNode in myTag1.Elements("MYTAG2")  
              select new EPTableItem  
              {  
                  //    Assign stuff here                              
              };  
}
+2
source

- .

static IEnumerable<XElement> ElementAndChildren(this XElement parent, string name, string childName) 
{
    var element = parent.Element(name);
    if (element == null)
    {
        return Enumerable.Empty<XElement>();
    }
    return element.Elements(childName);
}

...
var myItems = from myNode in Nodes.ElementAndChildren("MYTAG1","MYTAG2")
                       select new EPTableItem
                       {
                       //    Assign stuff here                            
                       };
+1

, Linq , sql. - , , .

var myItems = Nodes.Where(n => n.Element("MYTAG1") != null)
   .Select(n => n.Element("MYTAG1"))
   .Select(elem => elem.Elements("MYTAG2"))
   .Select(elem2 => new EPTTableItem { something = elem2.SomeProperty ... } );
+1
source

If you want to do this in LINQ, then something like this should work:

var myItems = from node in (from myNode in Nodes.Elements("MYTAG1")
              where myNode != null
              select myNode).SelectMany(x => x.Elements("MYTAG2"))
              select new EPTableItem
              {
                // Assign stuff here                            
              };

of course, this will work differently if more MYTAG cases appear

0
source

You can do all this in a single LINQ query with separate sentences and a where clause.

var myItems = 
        from tag1 in Nodes.Elements("MYTAG1")
        where tag1 != null
        from tag2 in tag1.Elements("MYTAG2")
        select new EPTableItem
        {
        //    Assign stuff here                            
        };
0
source

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


All Articles