-->

C# XML - Multiple Namespace Declaration with XML W

2019-02-23 00:51发布

问题:

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

回答1:

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



回答2:

You should pass your default namespace to the WriteStartElement method.



回答3:

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.



标签: c# xml xmlwriter