Search code examples
c#xmlencodingxmlwriter

Create start XML manually


I want to create XML file so i am using this way:

XmlWriterSettings settings = new XmlWriterSettings
                  {
                      Indent = true,
                      Encoding = Encoding.Unicode
                  };

string xmlPath = @"c:\file.xml";
XmlWriter xmlWriter = XmlWriter.Create(xmlPath, settings);
xmlWriter.WriteStartDocument(false);

Result:

<?xml version="1.0" encoding="utf-16" standalone="no"?>
<cp>
  <user>NA</user>
  <password>NA</password>
</cu>

But i want this start XML will be Upper case:

<?xml version="1.0" encoding="UTF-16" standalone="no"?>

So i try to create this start manually:

 XmlWriterSettings settings = new XmlWriterSettings
                   {
                        Indent = true,
                        Encoding = Encoding.Unicode
                   };

string xmlPath = @"c:\file.xml";
XmlWriter xmlWriter = XmlWriter.Create(xmlPath, settings);
xmlWriter.WriteRaw("<?xml version=\"1.0\" encoding=\"UTF-16\" standalone=\"no\"?>\r\n");

But the result was that i received the start twice:

<?xml version="1.0" encoding="utf-16"?><?xml version="1.0" encoding="UTF-16" standalone="no"?>

Solution

  • You can add the following line before you start writing the xml. That is,

    settings.OmitXmlDeclaration = true;
    string xmlPath = @"c:\file.xml";
    XmlWriter xmlWriter = XmlWriter.Create(xmlPath, settings);
    xmlWriter.WriteRaw("<?xml version=\"1.0\" encoding=\"UTF-16\" standalone=\"no\"?>\r\n");
    

    This way your xml will be created not with the default declaration, but with the one that you are adding exclusively.