XElement with colon in the name doesn't work [duplicate]

孤人 提交于 2019-12-25 03:17:04

问题


i'm trying to make something like :

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

but i doesn't work, and i got a error because of the colon ':'.

does anyone know how can I solve the problem ?


回答1:


That's not how you create an XName with a namespace.

You should create an XNamespace with the right URI, and then you can create the right XName easily - personally I use the + operator. So:

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

To use a specific namespace alias, you need to include an attribute with the xmlns namespace, which can be in a parent element.

Here's a complete example:

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

Output:

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

Obviously you need to use the right namespace URI though...



来源:https://stackoverflow.com/questions/23547349/xelement-with-colon-in-the-name-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!