缺少根元素 - 使用XmlTextWriter创建Xmldocument

NLV*_*NLV 7 .net c# xml

我有以下代码在吐出"根元素缺失"期间doc.Load().

MemoryStream stream = new MemoryStream();
XmlTextWriter xmlWriter = new XmlTextWriter(stream, Encoding.UTF8);
xmlWriter.Formatting = System.Xml.Formatting.Indented;
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Root");
XmlDocument doc = new XmlDocument();
stream.Position = 0;
doc.Load(stream);
xmlWriter.Close();
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚这个问题.任何见解?

Jon*_*eet 13

你没有冲过去xmlWriter,所以它可能还没有写出任何东西.此外,你永远不会完成根元素,所以即使它已经写出来了

<Root>
Run Code Online (Sandbox Code Playgroud)

它不会写出结束标记.您正在尝试将其作为完整文档加载.

我不确定XmlWriter在什么时候实际写出了元素的起始部分 - 不要忘记它也可能有写入的属性.用你能得到的代码写的最多的是<Root.

这是一个完整的程序,有效:

using System;
using System.IO;
using System.Text;
using System.Xml;

class Test
{
    static void Main(string[] args)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            XmlTextWriter xmlWriter = new XmlTextWriter(stream, Encoding.UTF8);
            xmlWriter.Formatting = System.Xml.Formatting.Indented;
            xmlWriter.WriteStartDocument();
            xmlWriter.WriteStartElement("Root");
            xmlWriter.WriteEndElement();
            xmlWriter.Flush();

            XmlDocument doc = new XmlDocument();
            stream.Position = 0;
            doc.Load(stream);
            doc.Save(Console.Out);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

(请注意,我没有打电话WriteEndDocument- 如果你仍然有开放的元素或属性,那似乎是必要的.)