使用文本编写器将多个元素添加到 XML C#
本文关键字:添加 XML 元素 文本编写器 | 更新日期: 2023-09-27 18:33:27
我需要以下输出
<BatchFile>
<BatchFileHeader>
<MessageType>MSG103</MessageType>
<Version>456</Version>
<BatchFileHeader>
<Vendor>
<VendorType>VVV</VendorType>
</Vendor>
</BatchFile>
以下是我的代码
StringWriter stringwriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringwriter);
xmlTextWriter.Formatting = Formatting.Indented;
xmlTextWriter.WriteStartDocument();
xmlTextWriter.WriteStartElement("BatchFileHeader");
xmlTextWriter.WriteElementString("MessageType", "MSG103");
xmlTextWriter.WriteElementString("MessageVersion", "456");
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("Vendor");
xmlTextWriter.WriteElementString("Vendor", "VVV");
xmlTextWriter.WriteEndElement();
但是我收到以下错误
状态 Epilog 中的标记起始元素将导致无效的 XML 公文
我做错了什么?
你忘了写最外面的 StartElement <BatchElement>
。
添加以下内容应该可以解决您的问题;
StringWriter stringwriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringwriter);
xmlTextWriter.Formatting = Formatting.Indented;
xmlTextWriter.WriteStartDocument();
xmlTextWriter.WriteStartElement("BatchElement");
xmlTextWriter.WriteStartElement("BatchFileHeader");
xmlTextWriter.WriteElementString("MessageType", "MSG103");
xmlTextWriter.WriteElementString("MessageVersion", "456");
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteStartElement("Vendor");
xmlTextWriter.WriteElementString("Vendor", "VVV");
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteEndElement();
xmlTextWriter.WriteEndDocument();