0

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?

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.