How to prevent XDocument from adding XML version and encoding information

痞子三分冷 提交于 2019-12-06 17:14:21

问题


Despite using the SaveOptions.DisableFormatting option in the following code:

XDocument xmlDoc = XDocument.Load(FileManager.SourceFile); 
string element="campaign";
string attribute="id";

var items = from item in xmlDoc.Descendants(element)                        
            select item;

foreach (XElement itemAttribute in items)
{
    itemAttribute.SetAttributeValue(attribute, "it worked!");
    //itemElement.SetElementValue("name", "Lord of the Rings Figures");
}

xmlDoc.Save(TargetFile, SaveOptions.DisableFormatting);

the target XML file gets this added to it:

<?xml version="1.0" encoding="utf-8"?>

Is there a way to preserve the original formatting and not have the version and encoding information added?


回答1:


That's the behaviour of the XDocument.Save method when serializing to a file or a TextWriter. If you want to omit the XML declaration, you can either use XmlWriter (as shown below) or call ToString. Refer to Serializing with an XML Declaration.

XDocument xmlDoc = XDocument.Load(FileManager.SourceFile); 

// perform your modifications on xmlDoc here

XmlWriterSettings xws = new XmlWriterSettings { OmitXmlDeclaration = true };
using (XmlWriter xw = XmlWriter.Create(targetFile, xws))
    xmlDoc.Save(xw);


来源:https://stackoverflow.com/questions/16681240/how-to-prevent-xdocument-from-adding-xml-version-and-encoding-information

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!