【问题标题】:How to prevent XDocument from adding XML version and encoding information如何防止XDocument添加XML版本和编码信息
【发布时间】:2013-05-16 21:12:12
【问题描述】:

尽管在以下代码中使用了 SaveOptions.DisableFormatting 选项:

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 文件将其添加到其中:

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

有没有办法保留原始格式而不添加版本和编码信息?

【问题讨论】:

  • 那不是格式化。它是文件的一部分。是什么问题导致您希望将其删除?
  • 我正在尝试使用省略该部分的现有 XML 文件创建合成数据。除了我的改动之外,我希望生成的 XML 文件尽可能接近原始文件。
  • 没有代码应该有这些指令的问题。如果有任何代码关心它,那么它就坏了,应该尽快修复。
  • Infopath Sharepoint 集成使用有时不需要 XML 声明的 XML 文件。那是微软的代码。

标签: c# xml .net-3.5 xml-declaration


【解决方案1】:

这是序列化到文件或TextWriterXDocument.Save 方法的行为。如果要省略 XML 声明,可以使用XmlWriter(如下所示)或调用ToString。参考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);

【讨论】:

    猜你喜欢
    • 2011-09-21
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 2018-12-14
    相关资源
    最近更新 更多