5

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

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

3

You should pass your default namespace to the WriteStartElement method.

Comments

0
writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");

Should be written as

writer.WriteAttributeString("xsi", "http://www.w3.org/2000/xmlns/", "http://www.w3.org/2001/XMLSchema-instance");

In that case the prefix xsi is registered at XML name table. Later use of http://www.w3.org/2001/XMLSchema-instance for parameter ns at a method of XmlWriter will prepend the XML namespace prefix of xsi.

URI of XML namespace xsi is also available at .NET by constant System.Xml.Schema.XmlSchema.InstanceNamespace.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.