简体   繁体   中英

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

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

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