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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With