如何将文档类型添加到 XDocument?
我有一个现有的 XDocument 对象,我想向其中添加 XML 文档类型。例如:
XDocument doc = XDocument.Parse("<a>test</a>");
我可以使用以下方法创建 XDocumentType:
XDocumentType doctype = new XDocumentType("a", "-//TEST//", "test.dtd", "");
但是如何将其应用于现有的 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将
XDocumentType
添加到现有XDocument
中,但它必须是第一个添加的元素。与此相关的文档含糊不清。感谢 Jeroen 在评论中指出使用
AddFirst
的便捷方法。这种方法允许您编写以下代码,该代码显示如何在XDocument
已有元素后添加XDocumentType
:或者,您可以使用
Add 方法将
XDocumentType
添加到现有的XDocument
中,但需要注意的是,不应存在其他元素,因为它必须位于第一个。另一方面,以下内容无效,并且会导致 InvalidOperationException:“此操作将创建结构不正确的文档。”
You can add an
XDocumentType
to an existingXDocument
, 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 theXDocumentType
after theXDocument
already has elements:Alternately, you could use the
Add
method to add anXDocumentType
to an existingXDocument
, but the caveat is that no other element should exist since it has to be first.On the other hand, the following is invalid and would result in an InvalidOperationException: "This operation would create an incorrectly structured document."
只需将其传递给
XDocument
构造函数 (完整示例):或使用
XDocument.Add
(< code>XDocumentType 必须添加在根元素之前):Just pass it to the
XDocument
constructor (full example):or use
XDocument.Add
(theXDocumentType
has to be added before the root element):