为什么我的XDocument保存了我不需要的声明?我有以下代码:XElement("subelement1","1"),newXElement("subelement2","2"));vardoc=newXDocument(xml);doc.Declaration=null;文档.保存(流);我试过在没有xml声明的情况下保存XML,但即使我将XDocument的声明归零,它仍然被保存到最终的XML中。此代码输出:12相反,XDocument.Save()可以使用XmlWriter并使用System.IO将XmlWriterSettings.OmitXmlDeclaration设置为true;使用System.Xml;使用System.Xml.Linq;XmlWriterSettingsxws=newXmlWriterSettings();xws.OmitXmlDeclaration=true;xws.Indent=true;使用(varstream=File.Create(@"C:test.xml"))使用(XmlWriterxw=XmlWriter.Create(stream,xws)){varxml=newXElement("root",newXElement("subelement1","1"),newXElement("subelement2","2"));xml.保存(xw);您可以使用XmlWriter和自定义XmlWriterSettings执行此操作(您需要System.Xml的using指令):使用System.IO;使用System.Xml;使用System.Xml.Linq;类程序{staticvoidMain(string[]args){varxml=newXElement("root",newXElement("subelement1","1"),newXElement("subelement2","2"));vardoc=newXDocument(xml);varsettings=newXmlWriterSettings{OmitXmlDeclaration=true};使用(varstream=File.Create(@“test.xml”)){使用(varwriter=XmlWriter.Create(stream,设置)){doc.Save(作家);}}}}假设你想指定一个Stream——你也可以从一个文件名创建一个XmlWriter:}(如果不需要其他的XDocument,可以在根元素上用同样的方法调用Save)以上是C#学习教程:为什么我的XDocument保存了我不需要的语句?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
