开发者

C# XML to LINQ multiple elements with same name, how to get them to save in same object

开发者 https://www.devze.com 2023-02-25 17:02 出处:网络
I have the following codE: _logs.AddRange(elements .Select(log => new Log() { tid = (log.Element(\"tid\") == null) ? \"\" : log.Element(\"tid\").Value,

I have the following codE:

   _logs.AddRange(elements
                    .Select(log => new Log()
                         {
                             tid = (log.Element("tid") == null) ? "" : log.Element("tid").Value,
                             zid = (log.Element("zid") == null) ? "" : log.Element("zid").Value,
                             create = (log.Element("create") == null) ? "" : log.Element("create").Value,
                      开发者_StackOverflow社区       data = (log.Element("data") == null) ? null : log.Elements("data")
                             .Select(x => new Data() 
                             {
                                 data = (log.Element("data") == null) ?  "" : log.Element("data").Value

                             }).ToList()
                         }));

The data element shows up multiple times in each object. Why when it reads through these objects does it show x having the correct data but then when I look at _logs it shows only the first value.

For example if data looked like this:

<data>1</data>
<data>2</data>
<data>3</data>

So then the data list would show [0] = 1 , [1] = 1 , [2] = 1

Thanks


Your Select() is off, you are currently just selecting the value of the first item all over, instead do this:

.Select(x => new Data() 
{
    data = x.Value
}).ToList()

Also you don't need the initial null check - if there is no data element it will just be an enumeration with zero items, so this will work:

data =  log.Elements("data").Select( x=> new Data() { data = x.Value }).ToList()
0

精彩评论

暂无评论...
验证码 换一张
取 消