状态 Epilog 中的令牌 StartElement 将导致无效的 XML 文档

Token StartElement in state Epilog would result in an invalid XML document

我收到错误消息“状态 Epilog 中的标记 StartElement 会导致无效的 XML 文档。”当我从数据表中获取数据并尝试将其转换为 xml 文件时。

代码:

DataTable dtTest = new DataTable();
dtTest.Columns.Add("Name");
dtTest.Columns.Add("NickName");
dtTest.Columns.Add("Code");
dtTest.Columns.Add("reference");

dtTest.Rows.Add("Yash", "POPs", "Vapi", "None1");
dtTest.Rows.Add("shilpa", "shilpa", "valsad", "None2");
dtTest.Rows.Add("Dinesh", "dinu", "pune", "None3");
dtTest.Rows.Add("rahul", "mady", "pardi", "None4");
XmlWriterSettings settings = new XmlWriterSettings();

StringWriter stringwriter = new StringWriter();

XmlTextWriter xmlTextWriter = new XmlTextWriter(stringwriter);
xmlTextWriter.Formatting = Formatting.Indented;
xmlTextWriter.WriteStartDocument();
foreach (var row in dtTest.AsEnumerable())
{
        xmlTextWriter.WriteStartElement("");
        xmlTextWriter.WriteAttributeString("orderid", row.Field<string>("Name"));
        xmlTextWriter.WriteElementString("type",  row.Field<string>("Name"));
        xmlTextWriter.WriteElementString("status", row.Field<string>("Name"));
        xmlTextWriter.WriteElementString("productno", row.Field<string>("Name"));
        xmlTextWriter.WriteEndElement();
}
XmlDocument docSave = new XmlDocument();
docSave.LoadXml(stringwriter.ToString());

此错误的原因是什么,如何解决?

你这里有几个问题:

  1. 您正在向文档写入多个根元素,每次调用 xmlTextWriter.WriteStartElement("") 一个。但是,一个格式良好的 XML 文档必须有一个且只有一个 root element,因此您需要将行元素包装在某个容器元素中。

    (你可能一直认为 WriteStartDocument() 会写根元素,但它没有。它只是写了 XML 声明。)

  2. 您正在使用 XmlTextWriter,但此 class 已弃用。来自 docs:

    Starting with the .NET Framework 2.0, we recommend that you create XmlWriter instances by using the XmlWriter.Create method and the XmlWriterSettings class to take advantage of new functionality.

    如果您切换到 XmlWriter,您将获得更清晰的错误消息和更好的错误检查。

  3. 您正在尝试编写 没有名称的元素:

    xmlTextWriter.WriteStartElement("");
    

    这会导致格式错误 XML。 XmlTextWriter 似乎不检查这个,但 XmlWriter 会检查。

将以上所有内容放在一起,您的代码可以修改如下:

var stringwriter = new StringWriter();
using (var xmlWriter = XmlWriter.Create(stringwriter, new XmlWriterSettings {  Indent = true }))
{
    xmlWriter.WriteStartDocument();
    xmlWriter.WriteStartElement("Root");
    foreach (var row in dtTest.AsEnumerable())
    {
        xmlWriter.WriteStartElement("Row");
        xmlWriter.WriteAttributeString("orderid", row.Field<string>("Name"));
        xmlWriter.WriteElementString("type",  row.Field<string>("Name"));
        xmlWriter.WriteElementString("status", row.Field<string>("Name"));
        xmlWriter.WriteElementString("productno", row.Field<string>("Name"));
        xmlWriter.WriteEndElement();
    }
    xmlWriter.WriteEndElement();
}
var xml = stringwriter.ToString();

演示 fiddle here.