我有一个现有的XDocument对象,我想添加一个XML文档类型。例如:
XDocument doc = XDocument.Parse("<a>test</a>");
我可以使用以下代码创建XDocumentType:
XDocumentType doctype = new XDocumentType("a", "-//TEST//", "test.dtd", "");
但是我如何将它应用于现有的XDocument?
我有一个现有的XDocument对象,我想添加一个XML文档类型。例如:
XDocument doc = XDocument.Parse("<a>test</a>");
我可以使用以下代码创建XDocumentType:
XDocumentType doctype = new XDocumentType("a", "-//TEST//", "test.dtd", "");
但是我如何将它应用于现有的XDocument?
你可以向现有的XDocument
中添加一个XDocumentType
,但它必须是第一个添加的元素。有关此内容的文档描述比较模糊。
感谢Jeroen在评论中指出使用AddFirst
的便捷方法。这种方法允许你编写以下代码,展示了如何在XDocument
已经有元素后添加XDocumentType
:
var doc = XDocument.Parse("<a>test</a>");
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("<a>test</a>"));
XDocument
中的第一个元素。你可以使用xDocument.AddFirst(documentType)
而不是xDocument.Add(documentType)
来实现这一点。 - Jeroen Huinink