如何添加一个文档类型一个XDocument? [英] How do I add a document type to an XDocument?
问题描述
我有一个现有的XDocument对象,我想一个XML文档类型添加到。例如:
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>");
我可以通过创建一个XDocumentType:
I can create an XDocumentType using:
XDocumentType doctype = new XDocumentType("a", "-//TEST//", "test.dtd", "");
但我怎么它应用到现有的XDocument?
But how do I apply that to the existing XDocument?
推荐答案
您可以添加 XDocumentType
到现有的的XDocument
的,但它必须是第一个元素添加。文档周围,这是模糊的。
You can add an XDocumentType
to an existing XDocument
, but it must be the first element added. The documentation surrounding this is vague.
感谢吉荣在评论指出使用 addfirst仅
的方便的方法。这种方法允许你写下面的代码,它显示了如何添加 XDocumentType
的的XDocument
已经有元素后:
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);
另外,你可以使用添加
方法到 XDocumentType
添加到现有的的XDocument
,但需要注意的是,没有其他元素应该存在,因为它必须是。第一个
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);
在另一方面,下面是无效的,并会导致一个InvalidOperationException:此操作将创建。不正确的结构化文档
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
这篇关于如何添加一个文档类型一个XDocument?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!