【问题标题】:Why is a namespace prefix being added to my XML attribute?为什么要在我的 XML 属性中添加命名空间前缀?
【发布时间】:2020-12-13 16:31:30
【问题描述】:

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 的前缀。

为什么?

【问题讨论】:

  • 请编辑您的帖子并添加所需的输出。

标签: c# .net xml xml-namespaces xmltextwriter


【解决方案1】:

代码级答案

因为

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

将attribute 放入www.windward.net,并使用命名空间前缀进行关联。

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

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

XML 级答案

更新以解决 OP 评论:

我想要的是属性具有命名空间www.windward.net,但没有前缀。我该怎么做?

这相当于希望将默认命名空间应用于属性,这与 XML Namespace recommendation 相反:

默认命名空间声明不直接应用于属性名称;无前缀属性的解释由它们出现的元素决定。

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


另见

【讨论】:

  • 我想要的是属性具有命名空间 www.windward.net,但没有前缀。我该怎么做?
  • @DavidThielen:答案已扩展以解决您的后续问题。
  • 哦,好的。按照你的解释,这很有意义。
  • @GSerg:答案已更新,包括两个相关 Q/A 链接中更好的一个,以及另一个有用的 Q/A 链接。谢谢。
猜你喜欢
  • 2018-07-12
  • 1970-01-01
  • 2013-09-24
  • 2012-05-27
  • 1970-01-01
  • 1970-01-01
  • 2015-08-11
  • 2021-12-14
相关资源
最近更新 更多