Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# XML - Multiple Namespace Declaration with XML Writer

Tags:

c#

xml

xmlwriter

I am trying to create an XML document with multiple namespaces using System.Xml.Xmlwriter in C# and am recieving the following error on compile:

The prefix '' cannot be redefined from '' to 'http://www.acme.com/BOF' within the same start element tag.

The entirety of my code is below:

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

        XmlWriter writer = XmlWriter.Create("C:\\ACME\\xml.xml", settings);

        writer.WriteStartDocument();

        writer.WriteStartElement("BOF");
        writer.WriteAttributeString("xmlns", null, null, "http://www.acme.com/BOF");  //This is where I get my error
        writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
        writer.WriteAttributeString("fileName", null, null, "test.xml");
        writer.WriteAttributeString("date", null, null, "2011-10-25");
        writer.WriteAttributeString("origin", null, null, "MYORIGIN");
        writer.WriteAttributeString("ref", null, null, "XX_88888");
        writer.WriteEndElement();

        writer.WriteStartElement("CustomerNo");
        writer.WriteString("12345");
        writer.WriteEndElement();

        writer.WriteEndDocument();

        writer.Flush();
        writer.Close();

What am I doing wrong?

Thanks

John

like image 865
JMK Avatar asked Oct 26 '11 09:10

JMK


2 Answers

writer.WriteStartElement("BOF"); // write element name BOF, no prefix, namespace ""
writer.WriteAttributeString("xmlns", null, null, "http://www.acme.com/BOF");  //Set namespace for no prefix to "http://www.acme.com/BOF".

The second line makes no sense, because you're assigning the default (no-prefix) namespace to something other than what it is, in the same place as it is that.

Replace those two lines with writer.WriteStartElement("BOF", "http://www.acme.com/BOF")

like image 155
Jon Hanna Avatar answered Sep 20 '22 17:09

Jon Hanna


You should pass your default namespace to the WriteStartElement method.

like image 41
Frederik Gheysels Avatar answered Sep 19 '22 17:09

Frederik Gheysels