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:
WriteStartElement("A");
WriteStartElement("B");
// ... attributes or content added here will become part af B element
WriteEndElement(); // Closes the open B element.
WriteEndElement(); // Closes the open 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.
I agree with Cumbayah's answer, however you can alternatively use XmlTextWriter
's WriteElementString(string,string)
method if you just want an element with a value inside (no attributes, no child elements).
Example:
writer.WriteElementString("CustomerNo", "12345");
I highly recommend this as it will save a lot of space and make the code more readable.
Also, to really go the extra mile you could do:
writer.WriteElementString(XmlConvert.EncodeName("CustomerNo"), "12345");
Encode and Decode XML Element and Attribute Names and ID Values
The XmlTextWriter class does not perform character checks by default. For example, the code WriteElementString("Order Detail", "My order"), produces an invalid element of My order.
To encode the element value, the correct encoding is writer.WriteElementString(XmlConvert.EncodeName("Order Detail"), "My order") which produces the valid element My order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With