简体   繁体   中英

csv to xml using LINQ


I have ac# code in which I'm having a csv file containing customer data as follows:

ClientNumber1,Name1, BenefitCode1, EffectiveDt1 
ClientNumber1,Name1, BenefitCode2, EffectiveDt2 
ClientNumber2,Name2, BenefitCode3, EffectiveDt3 

Now in this case I want the output XML to have mutliple tags for Benefit within same customer (eg, the first two rows in my csv have same customer but two different benefits)

My output xml should be like

<Member>
<Num>ClientNumber1<Num>
<Nm>Name1</Nm>
 <Benefit>
  <Bc>BenefitCode1</Bc>
  <Dt>EffectiveDt1</Dt>
 </Benefit>
 <Benefit>
  <Bc>BenefitCode2</Bc>
  <Dt>EffectiveDt2</Dt>
 </Benefit>
</Member>
<Member>
<Num>ClientNumber1<Num>
<Nm>Name2</Nm>
 <Benefit>
   <Bc>BenefitCode3</Bc>
   <Dt>EffectiveDt3</Dt>
 </Benefit>
</Member>

So basically, while I performing the LINQ I should also be able to check it with previous ClientNum and in case I have the same num, the benefit data should be added within the same Member tag.

Thanks.

I would split this into two clearly separated steps:

1) Create data representation from file - by creating anonymous types, grouped by client number:

var data = File.ReadAllLines(@"C:\Desktop\test.csv")
               .Select(line => line.Split(','))
               .Select(parts => new
                {
                    ClientNumber = parts[0].Trim(),
                    Name = parts[1].Trim(),
                    BenefitCode = parts[2].Trim(),
                    EffectiveDate = parts[3].Trim()
                })
                .GroupBy(x => x.ClientNumber);

2) Save data as XML:

var xml = new XDocument(
        new XElement("SomeRoot",
                output.Select(e => new XElement("Member",
                        new XElement("Num", e.Key),
                        new XElement("Name", e.First().Name),
                        e.Select(x => new XElement("Benefit",
                            new XElement("Bc", x.BenefitCode),
                            new XElement("Dt", x.EffectiveDate)))
                    ))
            )
    );

Then you can save it to file with xml.Save(...)

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