By default, Unicode XML files generated in. Net contain BOM headers. However, some people in the group asked: What should I do if I do not want to generate this BOM header in some special circumstances?
I checked msdn and found a solution.
First, let's look at the default xmlwriter usage:
Public Static VoidWritefile () {xmlwritersettings settings =NewXmlwritersettings (); settings. indent =True; Settings. indentchars = ("");Using(Xmlwriter writer = xmlwriter. Create ("Books. xml", Settings )){// Write XML data.Writer. writestartelement ("Book"); Writer. writeelementstring ("Price","19.95"); Writer. writeendelement (); writer. Flush ();}}
In this way, the BOM is added to the xml header. To solve the problem, see the followingCode:
Public Static Void Writefile () {xmlwritersettings settings = New Xmlwritersettings (); settings. Encoding = New Utf8encoding ( False ); Settings. indent = True ; Settings. indentchars = (" "); Using (Xmlwriter writer = xmlwriter. Create ("Books. xml ", Settings )){ // Write XML data. Writer. writestartelement (" Book "); Writer. writeelementstring (" Price "," 19.95 "); Writer. writeendelement (); writer. Flush ();}}
We need to set a new encoding instance for the settings object. This instance will not add Bom. The BOM is added to the default instance.
Note that the constructor has passed the false parameter, which will notify the encoding instance not to write the BOM.
The output results of the two code segments are as follows:
We can find that the previous file has three more bytes in the header, namely ef bb bf, which is the BOM mark. Haha.