XML Error help

  • Thread starter Thread starter Vishal Bhavsar
  • Start date Start date
V

Vishal Bhavsar

Hello,

I am fairly new to C# so bear with me if this is a simple question... I
couldn't find much help searching for it on the web.
Ok so I am trying to generate an XML document using the XmlTextWriter
class. Here's the pseudo/code :


XmlTextWriter writer = new XmlTextWriter(stream, Encoding.ASCII);

writer.WriteStartDocument(true);
bool doOnce = true;

foreach(String item in myArray)
{
if (doOnce == true)
{
writer.WriteStartElement("root", "");
writer.WriteAttributeString("rootattribute", "1");
doOnce = false;
}

writer.WriteStartElement("node", "");

writer.WriteElementString("name", "vishal");
if (checkBox.Checked)
writer.WriteAttributeString("type", "admin");
else
writer.WriteAttributeString("type", "guest");

if (checkBox2.Checked)
{
writer.WriteElementString("country", countryText.Text);
}

... // more if statements of the same kind.

writer.WriteEndElement();

}
writer.WriteEndElement();
writer.WriteEndDocument();

XmlDocument xd = new XmlDocument();
xd.Load(saveStream);

writer.Close();
stream.Close();
}


(Sincere apologies if this code is hard to read due to formatting)
This code compiles fine but the compiler points to an unhandled
exception of type "System.InvalidOperationException" occurring at the
line:
if (checkBox2.Checked)
and the additional information given is: "Token StartAttribute in state
Content would result in an invalid XML document"

I don't see any problems with the way the XMLElements are being formed.
Maybe you can make me see what's wrong. Any help will be greatly
appreciated!
 
Vishal Bhavsar said:
I am fairly new to C# so bear with me if this is a simple question... I
couldn't find much help searching for it on the web.
Ok so I am trying to generate an XML document using the XmlTextWriter
class. Here's the pseudo/code :

(Sincere apologies if this code is hard to read due to formatting)

In future, it would be appreciated if rather than apologising for it,
you'd fix it - if you fix it once, it saves several other people *each*
fixing it. It would also have been helpful to make it a *complete*
example that demonstrated the problem - see
http://www.pobox.com/~skeet/csharp/complete.html

Anyway, the problem itself is that you can't write an attribute in the
middle of thin air - you have to write it directly after starting an
element. Essentially, by the time you've done:

writer.WriteStartElement("node", "");
writer.WriteElementString("name", "vishal");

you've output:

<node>
<name>vishal</name>

so where would the attribute go?
 
Back
Top