如何prevent的XDocument从添加XML版本和编码信息 [英] How to prevent XDocument from adding XML version and encoding information

查看:156
本文介绍了如何prevent的XDocument从添加XML版本和编码信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管使用SaveOptions.DisableFormatting选项下面的code:

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);

目标XML文件中获取此添加到它:

the target XML file gets this added to it:

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

有没有一种方法,以preserve原来的格式,而不必添加的版本和编码信息?

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

推荐答案

序列化到一个文件或<$ C $时,这就是 XDocument.Save 方法的行为C>的TextWriter 。如果你想省略XML声明,您可以使用的XmlWriter (如下图所示),或致电的ToString 。参阅序列化XML声明

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);

这篇关于如何prevent的XDocument从添加XML版本和编码信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆