Reputation: 6945
I am reading an XML response, the XML looks like this:
<?xml version=""1.0"" encoding=""UTF-8""?>
<Errors>
<Error>Error Msg 1</Error>
<Error>Error Msg 2</Error>
</Errors>
I have classes for response:
public class Error
{
public string ErrorMessage { get; set; }
}
public class OrderCreationResponse
{
public Error[] Errors { get; set; }
...
}
and I try to create an OrderCreationResponse
using this code:
var orderCreationResponse = xDocument.Root
.Elements("Errors")
.Select(x => new OrderCreationResponse
{
Errors = x.Elements("Error").Select(c => new Error
{
ErrorMessage = (string) c.Element("Error").Value
}).ToArray()
}).FirstOrDefault();
But it always returns null
. What am I doing wrong?
Upvotes: 0
Views: 70
Reputation: 26223
Your xDocument.Root
is your Errors
element, so it has no Errors
element beneath it. You are also making a similar mistake with Error
- you are already in that element when you're looking for more beneath it.
Change it to:
var orderCreationResponse = xDocument
.Elements("Errors")
.Select(x => new OrderCreationResponse
{
Errors = x.Elements("Error")
.Select(c => new Error {ErrorMessage = c.Value})
.ToArray()
}).FirstOrDefault();
Upvotes: 2