我正试图使用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>
您必须指定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
添加缩进。
试试这个。。。""
之前有
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();