11

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.

Giancarlo
  • 377
  • 2
  • 6
  • 16
  • You need to escape your quotes in that last line. For each literal `"` just put a `\"`. Look up escaping if you haven't come across this before. That having been said I am sure there are better ways to declare namespaced elements than that anyway. – Chris Dec 02 '13 at 17:19
  • See http://msdn.microsoft.com/en-us/library/cfche0ka(v=vs.110).aspx for some stuff on writing out namespaces properly. – Chris Dec 02 '13 at 17:20
  • Hi Chris, Thank you for your input, tried the escape \ which solves the error message but than gives: Invalid name character in 'ns0:NamespaceEnvelope xmlns:ns0="http://url.to.NamespaceEnvelope/v1.0"'. The ':' character, hexadecimal value 0x3A, cannot be included in a name. Than changed it to: writer.WriteStartElement("ns0"); writer.WriteAttributeString("xmlns", "ns0", null, "http://url.to.NamespaceEnvelope/v1.0"); Which gives me So now I need to get the last step to get – Giancarlo Dec 02 '13 at 17:53
  • Lol, the answer was just a bit lower on the external page: `writer.WriteStartElement("ns0", "NamespaceEnvelope", "http://url.to.NamespaceEnvelope/v1.0");` – Giancarlo Dec 02 '13 at 18:58

2 Answers2

24
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
Konstantin
  • 3,254
  • 15
  • 20
12
 private string RemoveXmlDefinition(string xml)
 {
    XDocument xdoc = XDocument.Parse(xml);
    xdoc.Declaration = null;

    return xdoc.ToString();
 }
Only a Curious Mind
  • 2,807
  • 23
  • 39