错误“<;节点名称>;没有预料到“;使用XmlWriter创建XML时
本文关键字:使用 XmlWriter XML 创建 节点 lt 错误 gt | 更新日期: 2023-09-27 17:59:30
我正在开发一个应用程序,我正在以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}
有什么想法吗?
感谢
您缺少XML文档中所需的根XML元素。只需这样添加:
<GasRoot>
<GasInfoEntries>
<Gallons>123</Gallons>
<Price>456</Price>
</GasInfoEntries>
<GasInfoEntries>
<Gallons>123</Gallons>
<Price>456</Price>
</GasInfoEntries>
</GasRoot>