0

..

I need help converting datatable to xml using Linq. I could do it with hardcoded column names as you can see in my code .. but i need it without hardcoding it ... hope could someone point me out how to do that .. thanks a alot

Example datatable ..

enter image description here

My linq query ..

    Dim xmlDoc As New XDocument(                           
             From row In dt.AsEnumerable()
                From row In dt.AsEnumerable()
                    Select New XElement("PUPIL",
                    New XAttribute("FIRSTNAME", row.Field(Of String)("First Name")),
                    New XAttribute("LASTNAME", row.Field(Of String)("Last Name")),
                    New XAttribute("DOB", row.Field(Of String)("Date of Birth")),
                    New XAttribute("Gender", row.Field(Of String)("Gender")),
                    New XAttribute("City", row.Field(Of String)("City"))
              ))
2
  • 1
    Is there a specific reason why you wouldn't simply use DataTable.WriteXml instead? Commented Apr 24, 2012 at 9:01
  • No .. I just love linq and want to improve my skills on it .. Commented Apr 24, 2012 at 12:59

1 Answer 1

3

Why not just load the columns from the row the same way you loaded the rows from the table?

Dim xmlDoc As New XDocument(
    From row In dt.Rows
        Select XElement("PUPIL",
            From column In dt.Columns
                Select
                    New XAttribute(column.Name, row.Item(column.Name))
         )
)
Sign up to request clarification or add additional context in comments.

2 Comments

This is brilliant Mr dbaseman ... Thanks so much ... just one more thing, how to improve my Linq skill ? any book or website you recommand ?
@LaurenceNyein this MSDN page has a ton of info (but it's MSDN, so a bit dry): msdn.microsoft.com/en-us/library/bb384508(v=vs.90).aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.