简体   繁体   中英

XDocument automatically indents files on parse and does not remove indent on save

I am seeking a help regarding file saving of XML file using XDocument (NOT XMLDocument).

So I have a xml file that does not have indentation (in fact it is 1 line). When I read this to XDocument using XDocument.Parse (after reading and storing string using StreamReader ), the resulting XDocument is indented.

Alright, I thought it will be fine as long as if I can save it back to the file without indentation. However, even though I have

XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.NewLineOnAttributes = false;
writerSettings.NewLineHandling = NewLineHandling.None;
writerSettings.Indent = false;

and pass that in when I create XmlWriter

using (var writer = XmlWriter.Create(u.ToFileSystemPath(), settings))
{
    xd.Save(writer);
}

The resulting XML file still has indentation. When I am debugging on Visual studio, I noticed that the writer is a class XmlWellFormedWriter . Does this have something to do with my result? Any help would be appreciated.

Thank you.

SaveOptions are available on Save() as well as ToString() .

    string xmlstring = 
@"<Top>
    <First>1</First>
    <Second>Dude</Second>
    <Third>Now</Third>
</Top>";

    XDocument doc = XDocument.Parse(xmlstring);
    doc.Save(@"C:\temp\noIndet.xml", SaveOptions.DisableFormatting);
        // string noIndent = doc.ToString(SaveOptions.DisableFormatting);

Output:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM