Create an XML file without the BOM header in. NET 2.0

Source: Internet
Author: User

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.
 
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.