How to export a DataTable to Xml with ALL columns as attributes?

前端 未结 5 1638
执笔经年
执笔经年 2020-12-31 18:58

Question: I\'m exporting a System.Data.DataTable to XML. So far it works fine. But I want to have all the data in attributes, which works fine as well. But my problem now, i

5条回答
  •  甜味超标
    2020-12-31 19:29

    Every XML attribute must be assigned a value that is enclosed in a pair of single or double quotation marks. There is no equivalent in plain text to denote a NULL value. A pair of quotation marks with no value to represent an empty string is not the same as a NULL value. Therefore, the only way to represent a NULL attribute is to omit the attribute.

    This means that you will need to either set AllowDBNull to false and assign a suitable DefaultValue on the DataColumn, or include the schema.

    Also, see Handling Null Values (ADO.NET)., particularly this section which explains the behavior:

    In addition, the following rules apply for an instance of DataRow.["columnName"] null assignments:

    1.The default default value is DbNull.Value for all except the strongly typed null columns where it is the appropriate strongly typed null value.

    2.Null values are never written out during serialization to XML files (as in "xsi:nil").

    3.All non-null values, including defaults, are always written out while serializing to XML. This is unlike XSD/XML semantics where a null value (xsi:nil) is explicit and the default value is implicit (if not present in XML, a validating parser can get it from an associated XSD schema). The opposite is true for a DataTable: a null value is implicit and the default value is explicit.

    4.All missing column values for rows read from XML input are assigned NULL. Rows created using NewRow or similar methods are assigned the DataColumn's default value.

    5.The IsNull method returns true for both DbNull.Value and INullable.Null.

提交回复
热议问题