C# creating XML output file without <?xml version=“1.0” encoding=“utf-8”?>

和自甴很熟 提交于 2019-11-30 02:54:56

问题


I'm new to C# development so maybe a very simple question here.

I'm trying to get an output which starts as this:

    <ns0:NamespaceEnvelope xmlns:ns0="http://url.to.NamespaceEnvelope/v1.0">

But am getting this:

    <?xml version="1.0" encoding="utf-8"?>
    <ns0>

This is my source:

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.IndentChars = "  ";
        settings.NewLineChars = "\r\n";
        settings.NewLineHandling = NewLineHandling.Replace;

        using (XmlWriter writer = XmlWriter.Create("employees.xml", settings))
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("ns0"); 
            writer.WriteStartElement("Firstsection");

How can I get rid of:

    <?xml version="1.0" encoding="utf-8"?>

And how can I change:

     writer.WriteStartElement("ns0"); 

To be able to output it as:

    <ns0:NamespaceEnvelope xmlns:ns0="http://url.to.NamespaceEnvelope/v1.0">

As this:

    writer.WriteStartElement("ns0:NamespaceEnvelope xmlns:ns0="http://url.to.NamespaceEnvelope/v1.0"");

Is asking for an ")" probably because of the "surrounding the http part.

Any help is highly appreciated.


回答1:


XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;



回答2:


 private string RemoveXmlDefinition(string xml)
 {
    XDocument xdoc = XDocument.Parse(xml);
    xdoc.Declaration = null;

    return xdoc.ToString();
 }


来源:https://stackoverflow.com/questions/20333973/c-sharp-creating-xml-output-file-without-xml-version-1-0-encoding-utf-8

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!