Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在XmlDocument中插入DOCTYPE元素_C#_.net_Xml - Fatal编程技术网

C# 如何在XmlDocument中插入DOCTYPE元素

C# 如何在XmlDocument中插入DOCTYPE元素,c#,.net,xml,C#,.net,Xml,我有一些生产代码,它以以下方式生成XML文件: 通过将XmlSerializer与具有XmlAttributes的类的实例一起使用来生成字符串 使用LoadXml()和步骤1中生成的字符串生成XmlDocument 使用XmlWriter包装StringWriter写入文件 现在需要包含DOCTYPE声明。我想对代码做尽可能少的更改 到目前为止,我做到这一点的唯一方法是: tx.WriteDocType("entitytype", null, "http://testdtd/entity.dtd

我有一些生产代码,它以以下方式生成XML文件:

  • 通过将XmlSerializer与具有XmlAttributes的类的实例一起使用来生成字符串
  • 使用LoadXml()和步骤1中生成的字符串生成XmlDocument
  • 使用XmlWriter包装StringWriter写入文件
  • 现在需要包含DOCTYPE声明。我想对代码做尽可能少的更改

    到目前为止,我做到这一点的唯一方法是:

    tx.WriteDocType("entitytype", null, "http://testdtd/entity.dtd", null);                    
    foreach (XmlNode node in document)
    {
      if (node.NodeType == XmlNodeType.XmlDeclaration)
      {
        document.RemoveChild(node);
      }
    }
    document.WriteTo(tx); 
    

    这似乎有点像黑客——有没有更好的方法插入DOCTYPE声明?具体来说,是否有一种方法可以避免在LoadXml()调用生成的XmlDocument中使用XmlDeclaration?

    可能需要更多的转换步骤,但在序列化时,可以使用
    XmlWriterSettings
    的实例按如下配置来删除xml声明

    var iSettings = new XmlWriterSettings{ OmitXmlDeclaration = true };
    

    感谢Codor的回答和讨论,尽管我的代码看起来与问题中的代码有很大的不同,但这些回答和讨论帮助我解决了这个问题

    我的XmlDocument也有一个XML声明,所以这对我来说很有用:

    XmlDocument doc = new XmlDocument();
    doc.Load(templateFilename);
    doc.InsertAfter(doc.CreateDocumentType("html", null, null, null), doc.FirstChild);
    

    否则,我想我会使用
    PrependChild()
    而不是
    InsertAfter()

    谢谢你的建议。在使用XmlWriter编写时,我希望包含一个XML声明—问题是添加到由LoadXml()创建的XmlDocument中的XML声明。在我可以使用WriteDocType()添加DOCTYPE之前,必须先删除此项。按照您的方式生成
    DOCTYPE
    inf对我来说似乎是正确的方式。我不知道OmitXmlDeclaration设置,它确实提供了一种不同的方法。因为它需要更多的步骤/改变,而且感觉不到任何清洁,我想我会坚持我原来的方法。