Search code examples
c#xmlstringxmlreaderxmlwriter

How To Write A String(XML Node formatted without root) as nodes using XMLWriter in C#?


I'm trying to write a string(which is nothing but XMLNodes) into a new XML File using XMLWriter

XmlWriter writer = XmlWriter.Create(@"C:\\Test.XML")
writer.WriteStartDocument();
writer.WriteStartElement("Test");

string scontent = "<A a="Hello"></A><B b="Hello"></B>";
XmlReader content = XmlReader.Create(new StringReader(scontent));
writer.WriteNode(content, true);
//Here only my first node comes in the new XML but I want complete scontent
writer.WriteEndElement();

Expected Output :

<Test>
<A a="Hello"></A>
<B b="Hello"></B>
</Test>

Solution

  • You must specify ConformanceLevel because your xml has no root element.

    Also always should dispose all used resources.

    using (XmlWriter writer = XmlWriter.Create(@"C:\\Test.XML"))
    {
        writer.WriteStartDocument();
        writer.WriteStartElement("Test");
    
        string scontent = "<A a=\"Hello\"></A><B b=\"Hello\"></B>";
    
        var settings = new XmlReaderSettings();
        settings.ConformanceLevel = ConformanceLevel.Fragment;
    
        using (StringReader stringReader = new StringReader(scontent))
        using (XmlReader xmlReader = XmlReader.Create(stringReader, settings))
        {
            writer.WriteNode(xmlReader, true);
        }
    
        writer.WriteEndElement();
    }
    

    In addition, you can use XmlWriterSettings to add indents.