我有一个现有的XDocument对象,我想添加一个XML doctype。例如:

XDocument doc = XDocument.Parse("<a>test</a>");

我可以使用:

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

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

有帮助吗?

解决方案

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

感谢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。添加 (必须在根元素之前添加 XDocumentType ):

XDocument doc = new XDocument();
doc.Add(new XDocumentType("a", "-//TEST//", "test.dtd", ""));
doc.Add(XElement.Parse("<a>test</a>"));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top