Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No implicit conversion between XNode and XElement

Tags:

linq-to-xml

I have two variables XResult, Xtemp of type XElement.

I am trying to extract all the <vehicle> elements from Xtemp and add them to Xresult under <vehicles>.

It seems that in Xtemp sometimes <vehicle> will appear under <vehicles>, and sometimes it will be by itself.

XResult.Descendants(xmlns + "Vehicles").FirstOrDefault().Add(
   XTemp.Descendants(xmlns + "Vehicles").Nodes().Count() > 0 
   ? XTemp.Descendants(xmlns + "Vehicles").Nodes() 
   : (XTemp.Descendants(xmlns + "SearchDataset").FirstOrDefault().Descendants(xmlns + "Vehicle")));

In the code above I am using the ternary operator to check if <vehicles> has childs then get all of them else go get all <vehicle> elements.

This produces the error: no implict conversion between System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> and System.Collections.Generic.IEnumerable <System.Xml.Linq.XElement>

Can some body help me correct this. Thanks in advance. BB.

like image 735
BumbleBee Avatar asked Feb 28 '26 18:02

BumbleBee


1 Answers

In the ternary you need to decide whether to use Nodes() or Descendants(). You can't have both. Nodes() returns an IEnumerable<XNode>, and Descendants() returns IEnumerable<XElement>. The ternary expressions need to return the same type.

Change:

XTemp.Descendants(xmlns + "Vehicles").Nodes()

to:

XTemp.Descendants(xmlns + "Vehicles").Nodes() 

Or you could add Nodes() to the second expression.

EDIT: if I understood your comment correctly you want to select each vehicle's nodes and itself. Try this in place of Descendants(xmlns + "Vehicle"):

.Descendants(xmlns + "Vehicle")
.SelectMany(d => d.DescendantNodesAndSelf().Take(1))

The Take(1) will allow you to grab the entire vehicle node and ignore all the other nodes that belong to it since I don't think you wanted those being repeated.

like image 191
Ahmad Mageed Avatar answered Mar 07 '26 09:03

Ahmad Mageed