简体   繁体   中英

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>

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.

Try this... with \\ before ""

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM