Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. For example:

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

I can create an XDocumentType using:

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

But how do I apply that to the existing XDocument?

like image 457
James Sulak Avatar asked Sep 11 '09 20:09

James Sulak


People also ask

Which method is used to search an XDocument?

In XDocument and XElement classes we can use two basic methods for querying: () – returns a collection of descendant elements, i.e., elements any level below current element's level. Elements () – returns a collection of child elements, i.e., elements only one level below current element's level.

What is an XDocument?

The XDocument class contains the information necessary for a valid XML document, which includes an XML declaration, processing instructions, and comments. You only have to create XDocument objects if you require the specific functionality provided by the XDocument class.


1 Answers

You can add an XDocumentType to an existing XDocument, but it must be the first element added. The documentation surrounding this is vague.

Thanks to Jeroen for pointing out the convenient approach of using AddFirst in the comments. This approach allows you to write the following code, which shows how to add the XDocumentType after the XDocument already has elements:

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.

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."

xDocument.Add(new XElement("Books"));
xDocument.Add(documentType);  // invalid, element added before doctype
like image 176
Ahmad Mageed Avatar answered Oct 06 '22 03:10

Ahmad Mageed