0

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/>
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
szMuzzyA
  • 136
  • 13
  • Please note that: Questions seeking debugging help (**"why isn't this code working?"**) must include the _desired behavior, a specific problem or error_ and the shortest code necessary to reproduce it in the question itself. Please include information about exception being thrown and the expected behavior or outcome you're trying to achieve. – Yurii Jan 07 '18 at 18:52
  • 2
    well, what does the exception message say? – Marc Gravell Jan 07 '18 at 18:55
  • @MarcGravell added one. Feel free to remove all comments from this post. – Alexei Levenkov Jan 07 '18 at 19:30

1 Answers1

4

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#.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Hans Kilian
  • 18,948
  • 1
  • 26
  • 35
  • 1
    It's great that this works, but what's the problem with OP's code? – Thomas Weller Jan 07 '18 at 19:06
  • 2
    WriteString is used to write a string value inside an XML element. There is no element when he wants to write, so it fails. – Hans Kilian Jan 07 '18 at 19:11
  • @HansKilian instead of adding explanation as comment you should have edited the post. I did it for you and added some more words you wanted to say about the approach. Now it is awesome answer suggesting better approach to what OP likely want, deserving upvote (versus original version that was borderline VLQ) – Alexei Levenkov Jan 07 '18 at 19:24