T-SQL has a FOR XML
clause that allows XML serialization from a rowset. This clause has a mode named as RAW
which serializes every row using an xml element and serialize its column values as element attribute values. For example, a rowset like the one below:
Column_1 Column_2
-------- --------
one 1
two 2
when serialized using raw mode gets serialized as follows:
<row Column_1="one" Column_2="1" />
<row Column_1="two" Column_2="2" />
This serialization mode is light and useful when column data uses basic types, because it is a less verbose than PATH
mode which serializes every column value using a xml element (requiring its open and close tags)
When a rowset from a System.Data.DataTable
instance is serialized from C# using WriteXml
methods it gets serialized as described for the PATH
mode of the T-SQL FOR XML
select clause. For the previous example it will result in something like
<DataSet>
<row><Column_1>one</Column_1><Column_2>1</Column_2></row>
<row><Column_1>two</Column_1><Column_2>2</Column_2></row>
</DataSet>
My question: is there a C# native way to serialize a System.DataTable
instance in the same way that SELECT FOR XML RAW(<element_name>)
does?
2条答案
按热度按时间enxuqcxy1#
Thanks to @siggemanen comment linking to this post I learned that the right way to configure how a datatable is serialized when its native WriteXml methods are invoked is to set the ColumnMapping property. In this case to map them as attributes the value is
MappingType.Attribute
This code shows the behaviorluaexgnf2#
Pretty simple, you can just use
XElement
and friends, along with LINQ.dotnetfiddle
If you want to use attributes, just change
new XElement(col.ColumnName, ...
to