使用textwriter将多个元素添加到XML C#

时间:2014-12-08 12:14:06

标签: c# xml xmlwriter

我需要以下输出

<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中的

令牌startelement会导致xml无效   文件

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您忘记编写最外层的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();