使用linq将datatable转换为xml

时间:2012-04-24 08:37:21

标签: xml vb.net linq datatable

...

我需要帮助使用Linq将datatable转换为xml。我可以用硬编码的列名来做,你可以在我的代码中看到..但我需要它而不需要硬编码...希望有人能指出我怎么做...感谢很多

示例数据表..

enter image description here

我的linq查询..

    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"))
              ))

1 个答案:

答案 0 :(得分:3)

为什么不加载行中的列的方式与从表中加载行的方式相同?

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))
         )
)
相关问题