szMuzzyA
szMuzzyA

Reputation: 126

Why does XmlWriter.WriteString("\n") throw an Exception?

I'm trying to write a new line after xml.WriteStartDocument(). When I do it throws an exception. It doesn't appear to throw an exception if I write it within the root element.

InvalidOperationException: Token Text in state Document would result in an invalid XML document.

So why does this not work? And how can I make it work?

using(XmlWriter xml = XmlWriter.Create(xmlFile))
{
  xml.WriteStartDocument();
  xml.WriteString("\n"); // <-- Exception
  // more nodes here
}

I'm trying to output new line between XML declaration and root node, as without it XmlWriter produces one single hard to read string. Desired output:

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

Upvotes: 0

Views: 825

Answers (1)

Hans Kilian
Hans Kilian

Reputation: 25389

WriteString is used to write a string value inside an XML element. There is no element when he wants to write, so it fails.

You can use:

xml.WriteRaw("\n");

Bewared that WriteRaw will write whatever you say exactly. I.e. if you decide to skip XML declaration at the beginning of the document and start "XML" with new line it will produce invalid XML. If you just want to achieve nicely looking XML - use Indentation and new line command for XMLwriter in C#.

Upvotes: 4

Related Questions