Khalil Khalaf
Khalil Khalaf

Reputation: 9407

Xml Writer: InvalidOperationException

I have the exact same routine to write data to a Xml file without any problems. Here I am trying to write a class instance data and on the first line I get this error:

Exception thrown: 'System.InvalidOperationException' in System.Xml.dll

In the Documentation it says that the writer is closed. How can I "open" it?

// stuff
XmlWriter writer = XmlWriter.Create(path + "\\" + this.Name);
writer.WriteStartDocument();

writer.WriteAttributeString("ID", this.Id.ToString()); // error pops here
writer.WriteAttributeString("Description", this.Description);
// other stuff

Upvotes: 1

Views: 1342

Answers (1)

Jan Köhler
Jan Köhler

Reputation: 6020

You're trying to write an attribute but you haven't written an element yet. So what you basically need to do is: create an element prior to writing an attribute:

writer.WriteStartElement("book");
writer.WriteAttributeString("ID", this.Id.ToString()); // ID becomes an attribute of "book"

What the documentation says is that the writer will be closed, when an InvalidOperationException is raised. By default it's open.

Edit:

Have another look at the docs :-)

When you use the XmlWriter methods to output XML, the elements and attributes will not be written until you call the Close method. For example, if you are using the XmlWriter to populate an XmlDocument, until you close the XmlWriter, you will not be able to observe the written elements and attributes in the target document.

So if you want the contents to be written to file, you'll have to flush or close the writer. You can do this via an explicit invocation (writer.Close()) or - maybe a bit nicer - with an using-statement, which disposes and closes the writer for you:

using(var writer = XmlWriter.Create(path + "\\" + this.Name))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("book");
    writer.WriteAttributeString("ID", this.Id.ToString());
    // even more elements etc.

} // .Close() is called implicitly for you

Edit2:

The resulting XML is written into a single line, because writing whitespace would just waste resources. XML can be written into a single line validly. But if you want the XML to be indented nicely and be human-readable, you'll have to specify that via XmlWriterSettings:

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

using(var writer = XmlWriter.Create(path + "\\" + this.Name, settings))
{
    // other code...

Upvotes: 3

Related Questions