首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将文档类型添加到XDocument?

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

Stack Overflow用户
提问于 2009-09-11 20:19:18
回答 2查看 12.6K关注 0票数 14

我有一个现有的XDocument对象,我想向其中添加一个XML doctype。例如:

代码语言:javascript
复制
XDocument doc = XDocument.Parse("<a>test</a>");

我可以使用以下命令创建XDocumentType:

代码语言:javascript
复制
XDocumentType doctype = new XDocumentType("a", "-//TEST//", "test.dtd", "");

但是我如何将其应用于现有的XDocument呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2009-09-11 20:47:45

您可以向现有XDocument添加XDocumentType,但它必须是添加的第一个元素。围绕这一点的文档是模糊的。

感谢Jeroen在评论中指出了使用AddFirst的便捷方法。这种方法允许您编写以下代码,该代码显示了如何在XDocument已有元素之后添加XDocumentType

代码语言:javascript
复制
var doc = XDocument.Parse("<a>test</a>");
var doctype = new XDocumentType("a", "-//TEST//", "test.dtd", "");
doc.AddFirst(doctype);

或者,您可以使用Add方法将XDocumentType添加到现有的XDocument中,但需要注意的是,不应该存在其他元素,因为它必须是第一个元素。

代码语言:javascript
复制
XDocument xDocument = new XDocument();
XDocumentType documentType = new XDocumentType("Books", null, "Books.dtd", null);
xDocument.Add(documentType);

另一方面,以下内容是无效的,会导致InvalidOperationException:“此操作将创建一个结构不正确的文档。”

代码语言:javascript
复制
xDocument.Add(new XElement("Books"));
xDocument.Add(documentType);  // invalid, element added before doctype
票数 16
EN

Stack Overflow用户

发布于 2009-09-11 20:46:56

只需将其传递给XDocument constructor (full example):

代码语言:javascript
复制
XDocument doc = new XDocument(
    new XDocumentType("a", "-//TEST//", "test.dtd", ""),
    new XElement("a", "test")
);

或者使用XDocument.Add ( XDocumentType必须添加在根元素之前):

代码语言:javascript
复制
XDocument doc = new XDocument();
doc.Add(new XDocumentType("a", "-//TEST//", "test.dtd", ""));
doc.Add(XElement.Parse("<a>test</a>"));
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1413053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档