如何使用LINQ to XML返回XElement?

One*_*key 0 xml linq xelement

我正在模拟将返回XElement的Web服务.该服务从数据库生成其XElement.为了获得本地测试服务,我创建了一个模拟XML元素列表的XML文档.我希望通过LINQ to XML选择并返回其中一个.

所以我有一个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>
Run Code Online (Sandbox Code Playgroud)

使用LINQ我想通过ordercode属性选择一个Customer元素.我只需要基本浏览客户节点的InnerXML并返回它.我尝试解析:

XElement xcust = (XElement)(from c in xdocument.Descendants("customer")
                 where c.Attribute("ordercode") == strorder
                 return c).Single();
Run Code Online (Sandbox Code Playgroud)

但它不起作用.我也尝试过:

return new XElement("customer", [same LINQ Query]);
Run Code Online (Sandbox Code Playgroud)

我猜我需要以某种方式询问所选客户的InnerXML的查询,但我不知道该怎么做.因为大多数人只是将XML直接解析为所需的对象(因为我正在模拟来自远程服务的响应,我无法做到),所以我只能返回原始元素时找不到太多信息,因为我猜这是一个一点边缘案例用法.

Bot*_*000 5

您需要检查属性的Value属性:

XElement xcust = (XElement)(from c in doc.Descendants("customer")
                 where c.Attribute("ordercode").Value == strorder
                 select c).Single();
Run Code Online (Sandbox Code Playgroud)

您也可以省略对XElement的强制转换.