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

标签 c# .net 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"),

执行此代码期间发生异常。

The ':' character, hexadecimal value 0x3A, cannot be included in a name.

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

最佳答案

要使用命名空间,您需要先创建命名空间对象:

已更新

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

关于c# - 如何在 XDocument 元素的名称中使用 ':' 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6125578/

相关文章:

c# - 开始现代游戏编程和应用程序编程的最佳方式是什么?

c# - Lambda 与 LINQ- "Expression is always false"

c# - 使用 Lambda 表达式堆叠 where 条件

javascript - 有没有一种工具可以从一种编程语言转换为另一种编程语言?

c# - IEnumerable<object[]> 和 IEnumerable<object>[] 之间的优雅转换

c# - 显式使用 "new EventHandler"声明有好处吗?

C# 访问子类属性

c# - linq where 子句导致异常

c# - 在 C# 中转义命令行参数

c# - 处理从 C++/MFC 应用程序中的 .NET dll 抛出的异常