简体   繁体   English

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

[英]How do I add a document type to an XDocument?

I have an existing XDocument object that I would like to add an XML doctype to. 我有一个现有的XDocument对象,我想向其中添加XML文档类型。 For example: 例如:

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

I can create an XDocumentType using: 我可以使用以下方法创建XDocumentType:

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

But how do I apply that to the existing XDocument? 但是,如何将其应用于现有的XDocument?

You can add an XDocumentType to an existing XDocument , but it must be the first element added. 您可以将XDocumentType添加到现有XDocument ,但是它必须是添加的第一个元素。 The documentation surrounding this is vague. 关于此的文档含糊不清。

Thanks to Jeroen for pointing out the convenient approach of using AddFirst in the comments. 感谢Jeroen指出了在注释中使用AddFirst的便捷方法。 This approach allows you to write the following code, which shows how to add the XDocumentType after the XDocument already has elements: 这种方法允许您编写以下代码,该代码显示XDocument已经具有元素之后如何添加XDocumentType

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

Alternately, you could use the Add method to add an XDocumentType to an existing XDocument , but the caveat is that no other element should exist since it has to be first. 或者,您可以使用Add方法将XDocumentType添加到现有XDocument ,但是要注意的是,因为必须是第一个元素,所以不应该存在其他任何元素。

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

On the other hand, the following is invalid and would result in an InvalidOperationException: "This operation would create an incorrectly structured document." 另一方面,以下内容无效,并会导致InvalidOperationException:“此操作将创建结构错误的文档。”

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

Just pass it to the XDocument constructor ( full example ): 只需将其传递给XDocument构造函数完整示例 ):

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

or use XDocument.Add (the XDocumentType has to be added before the root element): 或使用XDocument.Add (必须在根元素之前添加XDocumentType ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM