Friday 7 November 2014

Convert comma seperated string to xml structure using linq

Hello Developers,

While programming I came into the situation where
I need to convert comma separated string into XML structure using linq.

I searched a lot but no luck, at the end I decided to put
post on Codeproject.

One gentle guy help me there and solved my problem.

See here my code.

My string variable is:

var Query = "ID=265465,265466,265467,265468" + "|" +
"class=6,6,6,6" + "|" +
"name=ABC,DEF,GHI,JKL";

Output of this variable is:

ID=265465,265466,265467,265468|
class=6,6,6,6|
name=ABC,DEF,GHI,JKL


I want to convert this output into following XML structure

<Students>
    <stud>
        <ID>265465</ID>
        <class>6</class>
        <name>ABC</name>
    </stud>
    <stud>
        <ID>265466</ID>
        <class>6</class>
        <name>DEF</name>
    </stud>
    <stud>
        <ID>265467</ID>
        <class>6</class>
        <name>GHI</name>
    </stud>
    <stud>
        <ID>265468</ID>
        <class>6</class>
        <name>JKL</name>
    </stud>
</Students>

How to do achieve this using linq?

One guy wrote a code for me and solved my problem.

Code is here:

var Query = "ID=265465,265466,265467,265468" + "|" +
"class=6,6,6,6" + "|" +
"grade=A,B,C,D" + "|" +
"name=ABC,DEF,GHI,JKL";

var query = new XElement("Students",
from node0 in Query.Split('|')[0].Split('=')[1].Split(',').Select((item, index) => new { item, index })
select
new XElement("stud",
from n in Query.Split('|')
select new XElement(n.Split('=')[0], n.Split('=')[1].Split(',')[node0.index].Trim())
)
);

http://www.codeproject.com/Questions/839357/Convert-comma-seperated-string-to-xml-structure-us

Thank you guys......