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

9

我正在使用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"),

在执行此代码时发生了异常。

':'字符,十六进制值为0x3A,不能包含在名称中。

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


可能是使用XNamespace创建格式良好的XML的重复问题。 - H H
1个回答

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

更新

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

3
你还会注意到,':'不被使用,而是将命名空间与元素名称连接起来(这将导致一个XName)。 - Chris Chilvers
1
这个解决方案的结果是 <creator xmlns="dc"> 但我需要 dc:creator。 - user667429
1
这两个是等价的,“dc:”只是使用已经别名化的XML命名空间的简短方式(使用xmlns:dc =“…”声明)。 - Chris Chilvers
@user667429,我已经更新了答案,按照你的要求进行了格式化。 - Ken Pespisa
1
如果您想在输出中实际看到<dc:...,则必须添加适当的dc xmlns,请参见https://dev59.com/5W855IYBdhLWcg3wcz1h - Chris Chilvers

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接