Writing a string to an XML file without formatting (C #)

I wrote a function that builds an XML string based on the data stored in my application. Then, this line should be written to the actual XML file, so it can be used. This file should then be used in the HTML web application for submitting data. I use the following code snippet to do just that:

xmlDoc.Save("exercise.xml");

Easy, but there is a small catch. My XML file will not work properly in Firefox as it treats the space as childNode. Rewriting my entire web application to a large extent is not worth it, as it will be too much work. I would rather just save my XML string in an XML file in an unformatted way, as I tested and confirmed that this works in almost every conceivable browser. The line itself does not contain any carriage returns or tabs, so the Save () method probably adds it automatically. Any way to prevent this from happening, or another easy way to get around this?

+3
source share
5 answers

Try

xDoc.PreserveWhitespace = true;
xDoc.Save(...);
+3
source

XmlDocument.Save . , XML :

using (XmlWriter xw = XmlWriter.Create("exercise.xml", new XmlWriterSettings { Indent = false }))
    doc.Save(xw);
+9

You have a line containing working xml, why can't you just push it directly into a file using TextWriter / StreamWriter?

+1
source

I admit that I have not tested this, but hopefully this gives you a hint of a final decision

var xws = new XmlWriterSettings
{ 
    Indent = false, 
    NewLineOnAttributes = false 
};

using (var xtw = XmlTextWriter.Create("exercise.xml", xws))
{
    xmlDoc.Save(xtw);
}
+1
source

Did you try to just write your line that you created in the file? Something like that:

var myXML= "<root><node>something something something dark side</node></root>";
var file = new System.IO.StreamWriter("c:\\file.xml");
file.WriteLine(myXML);
file.Close();
+1
source

All Articles