我尝试使用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>
答案 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();