名称中带有冒号的XElement不起作用 [英] XElement with colon in the name doesn't work
问题描述
我正在尝试制作类似的东西:
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 ?
推荐答案
这不是使用命名空间创建 XName
的方法.
That's not how you create an XName
with a namespace.
您应该使用正确的URI创建 XNamespace
,然后可以轻松创建正确的 XName
-我个人使用的是 +
运算符.所以:
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", "");
要使用特定的名称空间别名,您需要在xmlns名称空间中包含一个属性,该属性可以位于父元素中.
To use a specific namespace alias, you need to include an attribute with the xmlns namespace, which can be in a parent element.
这是一个完整的例子:
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>
显然,您需要使用 right 名称空间URI,但...
Obviously you need to use the right namespace URI though...
这篇关于名称中带有冒号的XElement不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!