简体   繁体   English

LINQ to XML在C#中创建对象

[英]LINQ to XML create object in C#

I am reading an XML response, the XML looks like this: 我正在阅读XML响应,XML看起来像这样:

<?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: 我尝试使用以下代码创建OrderCreationResponse

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 . 但是它总是返回null What am I doing wrong? 我究竟做错了什么?

Your xDocument.Root is your Errors element, so it has no Errors element beneath it. xDocument.Root 您的Errors元素,因此它下面没有Errors元素。 You are also making a similar mistake with Error - you are already in that element when you're looking for more beneath it. 您还因Error犯了类似的Error -当您在该元素下寻找更多元素时,您已经在该元素中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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