XML 文档中存在错误 (1, 1) [英] There is an error in XML document (1, 1)
问题描述
我一直在尝试从 XML 读取数据.当我尝试反序列化它时,出现以下错误:
I have been trying to read data from XML. When I try to deserialize it, I get the following error:
XML 文档 (1, 1) 中存在错误."
"There is an error in XML document (1, 1)."
为了您的参考,我附上了我的整个代码以及我的 xml 文件.
For your reference, I am attaching my entire code as well as my xml file.
C# 代码:
CarCollection cars = null;
string path = @"C:\Users\harsha\Desktop\Doc.xml";
XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
var reader = XmlReader.Create(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();
另外,数据结构如下:
namespace XMLDataReader
{
[Serializable()]
public class Car
{
[System.Xml.Serialization.XmlElement("StockNumber")]
public string StockNumber { get; set; }
[System.Xml.Serialization.XmlElement("Make")]
public string Make { get; set; }
[System.Xml.Serialization.XmlElement("Model")]
public string Model { get; set; }
}
[Serializable()]
[System.Xml.Serialization.XmlRoot("CarCollection")]
public class CarCollection
{
[XmlArray("Cars")]
[XmlArrayItem("Car", typeof(Car))]
public Car[] Car { get; set; }
}
XML 文件:
<CarCollection>
<Cars>
<Car>
<StockNumber>1020</StockNumber>
<Make>Nissan</Make>
<Model>Sentra</Model>
</Car>
<Car>
<StockNumber>1010</StockNumber>
<Make>Toyota</Make>
<Model>Corolla</Model>
</Car>
<Car>
<StockNumber>1111</StockNumber>
<Make>Honda</Make>
<Model>Accord</Model>
</Car>
</Cars>
</CarCollection>
等待一些帮助.提前致谢!
Waiting for some help. Thanks in advance!
推荐答案
就我而言,不知何故,序列化程序中存在错误.我不确定是库还是逻辑.
In my case, somehow, there is a bug in the serializer. I am not sure whether it's the library or the logic.
检查你是否有和我一样的情况:
To check whether you have the same case like me:
- 从您的数据库列中复制您的 XML,
- 打开记事本,
- 将 xml 粘贴到记事本中,
- 保存
它会告诉你它有问题:
如果继续按确定,则再次打开文件.那里会有一个问号:
If you continue to press Ok, then open the file again. There will be a question mark there:
为了解决这个问题,在反序列化xml字符串之前,我只是检查第一个字符是否是天使括号.如果不是,则删除该字符:
To solve this, before deserializing the xml string, I simply check whether the first character is an angel bracket or not. If not, then remove that character:
private static string Validate(string xml)
{
if (string.IsNullOrEmpty(xml))
return xml;
try
{
var index = xml.IndexOf('<');
if (index > 0)
xml = xml.Substring(index);
}
catch { }
return xml;
}
这篇关于XML 文档中存在错误 (1, 1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!