我有两个变量XResult,Xtemp类型的Xtemp。
我正在尝试从Xtemp中提取所有<vehicle>
元素,并将它们添加到<vehicles>
下的Xresult。
似乎在Xtemp中,有时<vehicle>
会出现在<vehicles>
下,有时它本身会出现。
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")));
在上面的代码中,我使用三元运算符检查<vehicles>
是否有孩子,然后获取其他所有元素。
这会产生错误:<vehicle>
和System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode>
有些人可以帮我纠正这个问题。 提前致谢。 BB
答案 0 :(得分:2)
在三元组中,您需要决定是使用Nodes()
还是Descendants()
。你不能两者兼得。 Nodes()
返回IEnumerable<XNode>
,Descendants()
返回IEnumerable<XElement>
。三元表达式需要返回相同的类型。
变化:
XTemp.Descendants(xmlns + "Vehicles").Nodes()
为:
XTemp.Descendants(xmlns + "Vehicles").Nodes()
或者您可以将Nodes()
添加到第二个表达式。
编辑:如果我正确理解您的评论,您想要选择每个车辆的节点及其自身。试试这个代替Descendants(xmlns + "Vehicle")
:
.Descendants(xmlns + "Vehicle")
.SelectMany(d => d.DescendantNodesAndSelf().Take(1))
Take(1)
将允许您抓取整个车辆节点并忽略属于它的所有其他节点,因为我认为您不希望重复这些节点。