SoFunction
Updated on 2025-04-10

C# Method to extract full string from XmlDocument

Method 1: PassXmlDocumentofOuterXmlAttributes, seeXmlDocument class
The xml string obtained by this method is not formatted and has poor readability

Method 2: UtilizeXmlWriterSettingsControl format and other parameters, seeXmlWriterSettings class
example:

using ;
using ;
using ;
...
XmlDocument doc = new XmlDocument();
("<item><name>wrench</name></item>");
// Use XmlWriterSettings to control formatted outputXmlWriterSettings settings = new XmlWriterSettings
{
	Encoding = Encoding.UTF8,
    Indent = true,
    IndentChars = "  ", // Set indented characters and sizes    NewLineChars = "\r\n" // Set newline characters};
using (StringWriter textWriter = new StringWriter())
{
    using (XmlWriter xmlWriter = (textWriter, settings))
    {
        (xmlWriter); // Write XML to StringWriter    }
    string xmlString = (); // Get string    (xmlString);
}

passStringWriterAs an output stream, it is encoded according to UTF16 by default and cannot be changed. For example, the above XmlWriterSettings specifies UTF8 but the actual string is still UTF16
Use it insteadMemoryStreamAs a stream, you can customize the encoding, as follows:

using (MemoryStream ms = new MemoryStream())  
{
     using (XmlWriter xmlWriter = (ms, settings))
     {
         (xmlWriter); // Write XML to MemoryStream     }
     string xmlString = Encoding.(());  // Get string     (xmlString);
 }

This is the article about C# extracting complete strings from XmlDocument. For more related C# XmlDocument to extract string content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!