如何将文档类型添加到XDocument?

我有一个现有的XDocument对象,我想添加一个XML文档类型。 例如:

XDocument doc = XDocument.Parse("test"); 

我可以使用以下方法创建XDocumentType:

 XDocumentType doctype = new XDocumentType("a", "-//TEST//", "test.dtd", ""); 

但是,我如何将其应用于现有的XDocument?

您可以将XDocumentType添加到现有XDocument ,但它必须是添加的第一个元素。 围绕这个的文件是模糊的。

感谢Jeroen指出在评论中使用AddFirst的便捷方法。 此方法允许您编写以下代码,其中显示了在XDocument已有元素之后如何添加XDocumentType

 var doc = XDocument.Parse("test"); var doctype = new XDocumentType("a", "-//TEST//", "test.dtd", ""); doc.AddFirst(doctype); 

或者,您可以使用Add方法将XDocumentType添加到现有的XDocument ,但需要注意的是,不应存在其他元素,因为它必须是第一个。

 XDocument xDocument = new XDocument(); XDocumentType documentType = new XDocumentType("Books", null, "Books.dtd", null); xDocument.Add(documentType); 

另一方面,以下内容无效,并将导致InvalidOperationException:“此操作将创建一个不正确的结构化文档。”

 xDocument.Add(new XElement("Books")); xDocument.Add(documentType); // invalid, element added before doctype 

只需将它传递给XDocument构造函数 ( 完整示例 ):

 XDocument doc = new XDocument( new XDocumentType("a", "-//TEST//", "test.dtd", ""), new XElement("a", "test") ); 

或者使用XDocument.Add (必须在根元素之前添加XDocumentType ):

 XDocument doc = new XDocument(); doc.Add(new XDocumentType("a", "-//TEST//", "test.dtd", "")); doc.Add(XElement.Parse("test"));