3

I wrote a function that builds an XML string based on the data saved in my application. Next up, this string should be written to an actual XML file, so it can be used. This file is then to be used in an HTML web application to feed data. I'm using the following snippet of code to do just that:

xmlDoc.Save("exercise.xml");

Easy enough, but there's a small catch. My XML file won't work properly in Firefox, because it considers white space as a childNode. Rewriting my entire web application is pretty much a no go, as it'd be too much work. I'd rather just be able to save my XML string to an XML file in a non-formatted way, since I've tested and confirmed that this works in just about every conceivable browser. The string itself doesn't contain any carriage returns or tabs, so the Save()-method probably adds it automatically. Any way to prevent it from doing that, or another easy way to circumvent this?

1
  • 1
    Please can you post an example or the xml you're saving to file. Commented May 13, 2011 at 12:11

5 Answers 5

9

Take a look at this XmlDocument.Save overload. Here's a complete code example that saves XML without whitespace indentation:

using (XmlWriter xw = XmlWriter.Create("exercise.xml", new XmlWriterSettings { Indent = false }))
    doc.Save(xw);
Sign up to request clarification or add additional context in comments.

Comments

3

Try

xDoc.PreserveWhitespace = true;
xDoc.Save(...);

Comments

1

You have a string containing working xml, why cant you just push it out to file directly using TextWriter/StreamWriter?

1 Comment

To be honest it's been a long time since I last used the Text/StreamWriter (it's been months since I wrote any C# code at all), and I already had the writing of the xml file working, so I was hoping for a quick fix. But your point is valid of course, thanks for the input.
1

I admit I haven't tested this, but hopefully this gives you a hint towards the final solution

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

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

Comments

1

Have you tried just writing your string that you've built to a file? Something like this:

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

2 Comments

I think Zruty's answer is better but I'll leave mine up just in case.
I thought this would've take a lot more lines of code, thanks for the example!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.