如何在XDocument元素的名称中使用':'字符?

use*_*429 8 .net c# linq linq-to-xml special-characters

我正在使用XDocument在代码下面创建一个RSS:

var document = new XDocument(
    new XDeclaration("1.0", "utf-8", null),
    new XElement("rss",
                 new XElement("channel",
                              new XElement("title", "test"),
                              new XElement("dc:creator", "test"),
Run Code Online (Sandbox Code Playgroud)

执行此代码期间发生的异常.

':'字符,十六进制值0x3A,不能包含在名称中.

如何:在元素名称中使用字符?

Ken*_*isa 5

要使用名称空间,首先需要创建名称空间对象:

更新

XNamespace ns = "http://purl.org/dc/elements/1.1/";
var document = new XDocument(
            new XDeclaration("1.0", "utf-8", null),
            new XElement("rss", new XAttribute(XNamespace.Xmlns + "dc", ns)
                         new XElement("channel",
                                      new XElement("title", "test"),
                                      new XElement(ns + "creator", "test"),
            ....
Run Code Online (Sandbox Code Playgroud)

  • 而且你还会注意到':'没有被使用,而是将命名空间与元素的名称连接起来(这会产生一个XName). (3认同)