簡體   English   中英

使用C#將XML轉換為平面文件

[英]XML to Flat File using C#

我正在使用XMLDocumnet創建XML文件。 但是對於接口,我需要將它們共享為平面文件。 請幫忙。

XmlDocument doc1 = new XmlDocument();
            string loadFilePath = Server.MapPath("~\\temp\\IC35181.xml");
            doc1.Load(loadFilePath);

doc1.Save(Server.MapPath("~\\temp\\IC35181.xml"));

File.Copy(Server.MapPath("~\\temp\\IC35181.xml"), Server.MapPath("~\\temp\\IC35181_" + DateTime.Now.ToString("yyyyMMdd") + "_0" + (++k).ToString().PadLeft(4, '0') + ".xml"), true);

doc1.DocumentElement.ParentNode.RemoveAll();
File.WriteAllText(Server.MapPath("~\\temp\\IC35181.xml"), string.Empty);
File.Copy(Server.MapPath("~\\XMLRootTag.xml"),Server.MapPath("~\\temp\\IC35181.xml"), true);

如果需要控制格式,則不要使用XmlDocument.Save(string path) ,而要使用XmlDocument.Save(XmlWriter w) -您必須通過XmlWriter.Create(string, XmlWriterSettings)創建自己的XmlWriter

using(var writer = XmlWriter.Create(Server.MapPath("~\\temp\\IC35181.xml"), yourSettings))
{
    doc1.Save(writer);
}

然后,我們所需要做的就是確定要在XmlWriterSettings實例( yourSettings中為yourSettings中放入哪種格式設置。 也許:

var yourSettings = new XmlWriterSettings
{
    Indent = false,
    NewLineHandling = NewLineHandling.None,
    NewLineOnAttributes = false,
};

Marc的回答也對我有用,但是我發現了另外一個對我也有用的屬性:

doc1.PreserveWhitespace = true; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM