如何使用C#将DataRow转换为XML字符串?

时间:2021-11-18 01:37:33

I have a DataRow with columns col1 and col2. Each column has a value: val1 and val2 respectively. How can I turn this into an xml string using C#?

我有一个列col1和col2的DataRow。每列的值分别为:val1和val2。如何使用C#将其转换为xml字符串?

For the DataRow mentioned above I'd like the following string:

对于上面提到的DataRow,我想要以下字符串:

<col1>val1</col1><col2>val2</col2>

1 个解决方案

#1


5  

Put the DataRow into a new DataTable. Then call writeXml on the dataTable.

将DataRow放入新的DataTable中。然后在dataTable上调用writeXml。

Technically correct, but I would council against this, largely as you have no control over the XML outputted.

技术上是正确的,但我会反对这一点,主要是因为你无法控制输出的XML。

I would loop through the rows of the table and use the System.Linq.XML classes to properly format your XML (or if you're feeling more perverse, try XMLDocument and related classes)

我将循环遍历表的行并使用System.Linq.XML类来正确格式化XML(或者如果您感觉更不正常,请尝试XMLDocument和相关类)

#1


5  

Put the DataRow into a new DataTable. Then call writeXml on the dataTable.

将DataRow放入新的DataTable中。然后在dataTable上调用writeXml。

Technically correct, but I would council against this, largely as you have no control over the XML outputted.

技术上是正确的,但我会反对这一点,主要是因为你无法控制输出的XML。

I would loop through the rows of the table and use the System.Linq.XML classes to properly format your XML (or if you're feeling more perverse, try XMLDocument and related classes)

我将循环遍历表的行并使用System.Linq.XML类来正确格式化XML(或者如果您感觉更不正常,请尝试XMLDocument和相关类)