如何在C#中将文档类型添加到新的XML文件中

本文关键字:文件 XML 添加 文档 类型 | 更新日期: 2023-09-27 18:29:02

如何将以下文档类型添加到XML文件的开头

<!DOCTYPE smil PUBLIC "-//W3C//DTD SMIL 2.0//EN" "http://www.w3.org/2001/SMIL20/SMIL20.dtd">

我正在尝试使用C#XDocument创建一个XML文件,但不知道如何将以上内容添加到XML文件

如何在C#中将文档类型添加到新的XML文件中

的开头

您需要在XDocument:的开头添加一个XDocumentType

var xDocument = new XDocument(
  new XDocumentType(
    "smil",
    "-//W3C//DTD SMIL 2.0//EN",
    "http://www.w3.org/2001/SMIL20/SMIL20.dtd",
    null
  ),
  new XElement("Root")
);

您尝试过XmlDocument.CreateDocumentType()吗?MSDN链接

试试这个https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmldocument.createdocumenttype

//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
//Create a document type node and  
//add it to the document.
XmlDocumentType doctype;
doctype = doc.CreateDocumentType("book", null, null, "<!ELEMENT book ANY>");
doc.AppendChild(doctype);
//Create the root element and 
//add it to the document.
doc.AppendChild(doc.CreateElement("book"));