How do I return an XElement with LINQ to XML?
I am simulating a web service that will return an XElement. The service makes its XElement from a database. In order to have a local test service I have created an XML Document which simulates a list of XML Elements. I wish to select and return one of these via LINQ to XML.
So I have an XML Do开发者_运维问答cument:
<?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>
And using LINQ I would like to select one of the Customer elements by the ordercode Attribute. I just need to basically skim off the InnerXML of the customer node and return that. I tried parsing thus:
XElement xcust = (XElement)(from c in xdocument.Descendants("customer")
where c.Attribute("ordercode") == strorder
return c).Single();
but it didn't work. I also tried:
return new XElement("customer", [same LINQ Query]);
I'm guessing I need to somehow interrogate the query for the selected customer's InnerXML but I'm not sure how to do that. As most people just parse XML straight into the required objects (which as I'm simulating a response from a remote service I can't do) there's not much information that I can find on just returning the raw element as I guess this is a bit of an edge case usage.
You need to check the Value property of the Attribute:
XElement xcust = (XElement)(from c in doc.Descendants("customer")
where c.Attribute("ordercode").Value == strorder
select c).Single();
You can also omit the cast to XElement.
Of course, I was being stupid:
where c.Attribute("ordercode") == strorder
Should be:
where c.Attribute("ordercode").Value.ToString() == strorder.
Then it doesn't skip over it.
Try:
var res = (from c in xdocument.Element("customers").Elements()
let attr = c.Attribute("ordercode")
where attr != null && attr.Value == strorder
select c).Single();
精彩评论