如何在C#中使用XMLWriter将字符串(没有root格式化的XML节点)编写为节点?

时间:2016-04-29 12:19:31

标签: c# xml string xmlreader xmlwriter

我尝试使用XMLWriter将字符串(只是XMLNodes)写入新的XML文件

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

预期产出:

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

2 个答案:

答案 0 :(得分:2)

您必须指定ConformanceLevel,因为您的xml没有根元素。

也应始终处置所有使用的资源。

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

此外,您可以使用XmlWriterSettings添加缩进。

答案 1 :(得分:0)

\

之前使用""尝试此操作
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();