手动创建启动XML

时间:2018-03-22 08:48:52

标签: c# xml encoding xmlwriter

我想创建XML文件,所以我使用这种方式:

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

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

结果:

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

但是我希望这个启动XML将是Upper case

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

所以我尝试手动创建这个开始:

 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");

但结果是我收到了两次开始:

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

1 个答案:

答案 0 :(得分:0)

您可以在开始编写xml之前添加以下行。 也就是说,

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");

这样,您的xml将不是使用默认声明创建的,而是使用您要独占添加的声明。