Question

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 ?

Était-ce utile?

La solution

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...

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top