我试图弄清楚CreateDocumentType()在C#中工作,虽然我已经找到并读取了它上面的msdn页面,但我无法让它为我工作.
我只是想在我的xml文档中创建这一行:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Run Code Online (Sandbox Code Playgroud)
有人可以帮我解决这个问题所需的语法
编辑:代码到目前为止,htmldoc是在代码中进一步声明的xmldocument.
string dtdLink = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";
string dtdDef = "-//W3C//DTD XHTML 1.0 Transitional//EN";
XmlDocumentType docType = htmlDoc.CreateDocumentType("html", "PUBLIC", dtdLink, dtdDef);
htmlDoc.AppendChild(docType);
Run Code Online (Sandbox Code Playgroud)
这不起作用.
问候,
首先让我们来看一个简单的例子:
XmlDocument document = new XmlDocument();
XmlDocumentType doctype = document.CreateDocumentType("html", "-//W3C//DTD HTML 4.01//EN", "http://www.w3.org/TR/html4/strict.dtd", null);
document.AppendChild(doctype);
Run Code Online (Sandbox Code Playgroud)
如果您在开发人员IDE(Visual Studio,MonoDevelop,SharpDevelop)中运行此代码,您可能会在AppDomain的基本目录中获得一个DirectoryNotFoundException,引用 - // W3C // DTD HTML 4.01 // EN.如果继续执行此代码并在下载dtd时等待,您可能会收到带有消息的XmlException:' - '是一个意外的令牌.预期的标记是'>'.第81行,第5行.您可以继续执行此代码,xml文档将按预期输出.
您可以将此代码包装在try catch块中并等待它静静地抛出先前提到的异常并继续本文档,或者您可以将XmlResolver属性设置为null,并且文档不会尝试解析doctype.
解决原始问题:
调用CreateDocumentType的参数不正确.您不需要指定PUBLIC,应该交换dtdLink和dtdDef.以下是创建正确文档类型节点的原始发布的修订版.
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string dtdLink = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";
string dtdDef = "-//W3C//DTD XHTML 1.0 Transitional//EN";
// Create an xml document
XmlDocument htmlDoc = new XmlDocument();
/// Set the XmlResolver property to null to prevent the docType below from throwing exceptions
htmlDoc.XmlResolver = null;
try
{
// Create the doc type and append it to this document.
XmlDocumentType docType = htmlDoc.CreateDocumentType("html", dtdDef, dtdLink, null);
htmlDoc.AppendChild(docType);
// Write the root node in the xhtml namespace.
using (XmlWriter writer = htmlDoc.CreateNavigator().AppendChild())
{
writer.WriteStartElement("html", "http://www.w3.org/1999/xhtml");
// Continue the document if you'd like.
writer.WriteEndElement();
}
}
catch { }
// Display the document on the console out
htmlDoc.Save(Console.Out);
Console.WriteLine();
Console.WriteLine("Press Any Key to exit");
Console.ReadKey();
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,此代码适用于带有Mono的MS Windows和Linux.祝您好运.