简体   繁体   中英

LINQ to XML create object in C#

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM