Why is a namespace prefix being added to my XML attribute?

530 views Asked by At

I have a fiddle here:

using System;
using System.Xml;
using System.IO;
using System.Text;
                    
public class Program
{
    public static void Main()
    {
        Console.WriteLine("Starting");
        MemoryStream stream = new MemoryStream();
        var utf = new UTF8Encoding(false);
        XmlTextWriter writer = new XmlTextWriter(stream, utf);
        writer.Formatting = Formatting.Indented;
        writer.WriteStartDocument();
        
        writer.WriteProcessingInstruction("process", "5");
        writer.WriteComment("commenting");
        
        writer.WriteStartElement("dog");
        writer.WriteAttributeString("attribute", "www.windward.net", "5");
        
        writer.WriteStartElement("cat");
        
        writer.WriteEndElement();
        writer.WriteEndElement();
        writer.WriteEndDocument();
        writer.Flush();
        
        string result = utf.GetString(stream.ToArray(), 0, (int) stream.Length);
        Console.WriteLine("XML: " + result);
    }
}

I am adding an attribute with a no prefix namespace. It is creating a prefix of d1p1.

Why?

1

There are 1 answers

5
kjhughes On BEST ANSWER

Code-level answer

Because

    writer.WriteAttributeString("attribute", "www.windward.net", "5");

places attribute into the www.windward.net, and the namespace prefix is used to make the association.

If you want attribute to be in no namespace, remove the "www.windward.net" namespace argument:

    writer.WriteAttributeString("attribute", "5");

XML-level answer

Update to address OP comment:

What I want is for the attribute to have the namespace www.windward.net, but with no prefix. How can I do that?

That amounts to wanting default namespaces to apply to attributes, which is contrary to the XML Namespace recommendation:

Default namespace declarations do not apply directly to attribute names; the interpretation of unprefixed attributes is determined by the element on which they appear.

If you want those attributes to be in a namespace, accept the API's use of a namespace prefix to put them there.


See also