我有一个现有的XDocument对象,我想向其中添加一个XML doctype。例如:
XDocument doc = XDocument.Parse("<a>test</a>");我可以使用以下命令创建XDocumentType:
XDocumentType doctype = new XDocumentType("a", "-//TEST//", "test.dtd", "");但是我如何将其应用于现有的XDocument呢?
发布于 2009-09-11 20:47:45
您可以向现有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发布于 2009-09-11 20:46:56
只需将其传递给XDocument constructor (full example):
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>"));https://stackoverflow.com/questions/1413053
复制相似问题