How do I add a document type to an XDocument?

后端 未结 2 1068
迷失自我
迷失自我 2021-02-07 13:18

I have an existing XDocument object that I would like to add an XML doctype to. For example:

XDocument doc = XDocument.Parse(\"test\");
         


        
2条回答
  •  误落风尘
    2021-02-07 13:50

    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("test");
    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
    

提交回复
热议问题