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
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")
You should pass your default namespace to the WriteStartElement method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With