XmlElement and XmlDocument both inherit XmlNode, and both of them have WriteTo() method. You should be able to call XmlElement.WriteTo(XmlWriter) Method to solve your problem.
In addition, you don't need to care whether it has children, c# will handle it correctly.
A simple code example for my test:
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load(@"D:\test\xml\booksData.xml");
XmlElement root = doc.DocumentElement;
XmlElement elem = doc.CreateElement("price");
elem.InnerText = "19.95";
root.AppendChild(elem);
using (XmlTextWriter w = new XmlTextWriter(@"d:\test\xml\out.xml", Encoding.UTF8))
{
root.WriteTo(w);
}
}
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.