如何使用LINQ to XML返回XElement?
我正在模拟将返回XElement的Web服务。该服务从数据库中创建XElement。为了拥有本地测试服务,我创建了一个模拟XML元素列表的XML文档。我希望选择并通过LINQ将其中的一个返回到XML。如何使用LINQ to XML返回XElement?
所以我有一个XML文档:
<?xml version="1.0" encoding="utf-8" ?>
<customers>
<customer ordercode="GCT/12345A">
<title>Miss</title>
<initials>A</initials>
<surname>Customer</surname>
...
</customer>
<customer ordercode="GCT/12346A">
<title>Mrs</title>
<initials>AN</initials>
<surname>Other</surname>
...
</customer>
</customers>
而且使用LINQ我想选择由ordercode属性客户元素之一。我只需要基本上删除客户节点的InnerXML并返回。我试着解析:
XElement xcust = (XElement)(from c in xdocument.Descendants("customer")
where c.Attribute("ordercode") == strorder
return c).Single();
但它没有工作。我也试过:
return new XElement("customer", [same LINQ Query]);
我猜我需要以某种方式查询所选客户的InnerXML查询,但我不知道该怎么做。由于大多数人只是将XML直接解析为所需的对象(因为我模拟远程服务的响应,我不能这么做),因此我只能返回原始元素,因为我猜测这是一个一个边缘案例使用的位。
您需要检查属性的Value属性:
XElement xcust = (XElement)(from c in doc.Descendants("customer")
where c.Attribute("ordercode").Value == strorder
select c).Single();
也可以省略剧组来的XElement。
当然,我太傻了:
where c.Attribute("ordercode") == strorder
应该是:
where c.Attribute("ordercode").Value.ToString() == strorder.
然后,它不随它跳过。
仅供参考'ToString()'不需要,因为'Value'返回'string'。 – 2011-03-16 13:49:55
叫我偏执狂;) – 2011-03-16 13:58:59
尝试:
var res = (from c in xdocument.Element("customers").Elements()
let attr = c.Attribute("ordercode")
where attr != null && attr.Value == strorder
select c).Single();
你是正确的,但它应该是'Attribute'不'Attributes'(去掉 “的”)。另外,可以省略对'XElement'的转换。 – 2011-03-16 13:46:15
我注意到了,我想我在复制粘贴原始代码时太快了:) – Botz3000 2011-03-16 13:47:12
完全正确,我最初使用了Attribute。属性是我的一个错字。 – 2011-03-16 13:48:36