asp.net - 名称中带有冒号的 XElement 不起作用

标签 asp.net c#-4.0 xelement

<分区>

我正在尝试做类似的东西:

new XElement("media:thumbnail", new XAttribute("width", ""))

但我不工作,因为冒号':'我得到了一个错误。

有谁知道我该如何解决这个问题?

最佳答案

这不是创建带有命名空间的 XName 的方式。

您应该使用正确的 URI 创建一个 XNamespace,然后您可以轻松创建正确的 XName - 我个人使用 + 运算符.所以:

XNamespace media = "... some URI here ...";
XElement element = new XElement(media + "thumbnail", new XAttribute("width", "");

要使用特定的命名空间别名,您需要包含一个带有 xmlns 命名空间的属性,该属性可以在父元素中。

这是一个完整的例子:

using System;
using System.Xml.Linq;

public class Test
{
    static void Main()
    {
        XNamespace ns = "http://someuri";
        var root = new XElement("root", 
                                new XAttribute(XNamespace.Xmlns + "media", ns),
                                new XElement(ns + "thumbnail", "content"));
        Console.WriteLine(root);        
    }
}

输出:

<root xmlns:media="http://someuri">
  <media:thumbnail>content</media:thumbnail>
</root>

显然您需要使用正确的 namespace URI...

关于asp.net - 名称中带有冒号的 XElement 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23547349/

相关文章:

c# - 创建 WCF ChannelFactory<T>

c#-4.0 - 如何在运行时使用Reflection.emit创建方法

C#检查xml文件中的元素

c# - LinQ to XML 访问元素及其值

c# - 从 Input 控件获取数据到代码隐藏

c# - 继承 ApiController 与 IHttpController 的区别

c# - List<T> 和 LinkedList<T> 的区别

c# - 如何转换为 List<IEnumerable<XElement>>

c# - 我如何遍历 PropertyCollection

c# - C# Web 应用程序的项目属性页面上不提供“调试”选项卡