为什么要将名称空间前缀添加到我的 XML 属性?

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

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);
    }
}

我正在添加一个没有前缀命名空间的属性。它正在创建 d1p1.

的前缀

为什么?

代码级答案

因为

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

attribute放入www.windward.net,命名空间前缀用于建立关联。

如果您希望 attribute 不在命名空间中,请删除 "www.windward.net" 命名空间参数:

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

XML级答案

更新以解决 OP 评论:

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

这相当于希望将默认命名空间应用于属性,这与 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.

如果您希望这些属性位于命名空间中,请接受 API 使用命名空间前缀将它们放在那里。


另见

  • XML attribute names and elements in default namespace?
  • XML namespaces and attributes