How can I write an XmlElement to an XmlTextWriter, where the element may have children

David Thielen 2,421 Reputation points
2020-12-13T20:27:24.357+00:00

Hi all;

Is there an easy (single call) way in .NET to write an XmlElement to a XmlTextWriter where that element is written out in full to the output?

Where the XmlElement may have many child elements and they have children, etc. And where it explicitly adds namespaces as needed.

thanks - dave

.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,135 questions
{count} votes

Accepted answer
  1. Timon Yang-MSFT 9,576 Reputation points
    2020-12-16T06:39:58.167+00:00

    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.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful