【发布时间】:2016-01-10 20:55:25
【问题描述】:
最近,我一直在处理使用两个命名空间的文档。我已经能够创建使用不同名称空间的多个 XElement,例如已在此处回答: How to load and add elements in an XML tree
问题是我需要将两个 dc 和 opf 命名空间组合在同一个元素中,但我不知道该怎么做。我使用这段代码来创建一个 XML 元素:
//open the opf file as an LINQ XML document.
XDocument opfDoc = XDocument.Load(opfFile);
//create the xmlnamespaces required for the <metadata> section of the opf file.
var dc = (XNamespace)"http://purl.org/dc/elements/1.1/";
var opf = (XNamespace)"http://www.idpf.org/2007/opf";
//**add book metadata
meta.Add(new XElement(dc + "creator", bookCreators[0].bookCreator));
输出如下:
<dc:creator>Author Name</dc:creator>
我需要做的是添加一个或多个使用另一个命名空间的附加属性,因此代码输出如下:
<dc:creator opf:file-as="Name, Author">Author Name</dc:creator>
我试着写了这段代码……
meta.Add(new XElement(dc + "creator",
new XmlAttribute(opf + "file-as", bookCreators[0].bookCreatorFileAs),
bookCreators[0].bookCreator));
...但我不断收到此错误消息:
xattribute 不包含带有两个参数的构造函数
您能推荐一种解决此问题的方法吗?
谢谢。
【问题讨论】:
-
一方面,您混淆了 XAttribute 和 XmlAttribute。解决这个问题可能会解决您的问题。
-
你是对的。我错误地添加了 XmlAttribute 而不是 XAttribute。
标签: c# xml visual-studio namespaces