使用XmlWriter </nodename>创建XML时出现错误“<期望<nodename>”

时间:2014-04-23 01:36:30

标签: c# xml

我正在处理一个应用程序,我以XML格式保存数据,但我在格式化方面遇到了问题。

输出看起来像这样

 <GasInfoEntries>
   <Gallons>123</Gallons>
   <Price>456</Price>
 </GasInfoEntries><GasInfoEntries>
   <Gallons>123</Gallons>
   <Price>456</Price>
 </GasInfoEntries>

我用它来写它

List<GasInfoEntries> data = new List<GasInfoEntries>();

                        data.Add(new GasInfoEntries() { Gallons = TxtBoxGas.Text, Price = TxtBoxPrice.Text });
                        xmlWriter.WriteStartDocument();
                        xmlWriter.WriteStartElement("GasInfoEntries");

                        xmlWriter.WriteStartElement("Gallons", "");
                        xmlWriter.WriteString(TxtBoxGas.Text);
                        xmlWriter.WriteEndElement();


                        xmlWriter.WriteStartElement("Price", "");
                        xmlWriter.WriteString(TxtBoxPrice.Text);
                        xmlWriter.WriteEndElement();

                        xmlWriter.WriteEndDocument();
                        xmlWriter.Flush();
                        //do i need?
                        xmlWriter.Close();

我收到此错误

- $exception
{System.InvalidOperationException: There is an error in XML document (1, 2). ---> System.InvalidOperationException: <GasInfoEntries xmlns=''> was not expected.
    at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderList1.Read3_ArrayOfGasInfoEntries()
    --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, Object events)
    at System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
    at LP_Buddy.MainPage.btnShow_Click(Object sender, RoutedEventArgs e)}
System.Exception {System.InvalidOperationException}

任何想法?

感谢

1 个答案:

答案 0 :(得分:0)

您缺少XML文档中所需的根XML元素。只需添加如下:

<GasRoot>
    <GasInfoEntries>
      <Gallons>123</Gallons>
      <Price>456</Price>
    </GasInfoEntries>
    <GasInfoEntries>
      <Gallons>123</Gallons>
      <Price>456</Price>
    </GasInfoEntries>
</GasRoot>