I’m using System.Xml to create an XML document in C#
My question is hopefully a simple one, do I need to use the WriteEndElement to close an XML tag?
For example, I have found that the following code will compile with or without ‘writer.WriteEndElement();’ and produce the same XML either way, however if I put ‘writer.WriteEndElement();’ twice, the program throws an exception.
writer.WriteStartElement("CustomerNo");
writer.WriteString("12345");
writer.WriteEndElement();
I’m not lazy and don’t mind putting this in where it needs to be if this is how it’s supposed to be, I just need some guidance here.
Thanks
John
Generally speaking: Yes, for each WriteStartElement() there must be a matching WriteEndElement().
Think of the containment hierarchy as a stack – the Starts (“pushes”) and Ends (“pops”) must balance. If you try to “pop” beyond the end, it’s a failure and an exception is thrown, like you describe.
As an example, to write a B element within the A element:
Update: As @Sam points out in another answer, when – as in the example you give – you want to only write out simple content elements (no attributes or child elements), you may want to take a look at the convenience method WriteElementString(), which automatically wraps the content in start/end tags.
Hope this helps.