我正在使用基于XML的.config文件来存储一些记录。 我的XML如下:
<?xml version="1.0" encoding="utf-8"?>
<Data_List xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Configuration>
<Name>1st Week</Name>
<Binary>
<Field>field1</Field>
<Version>1.0</Version>
</Binary>
<Binary>
<Field>field2</Field>
<Version>2.0</Version>
</Binary>
</Configuration>
<Configuration>
<Name>2nd Week</Name>
<Binary>
<Field>field1</Field>
<Version>2.0</Version>
</Binary>
<Binary>
<Field>field2</Field>
<Version>4.0</Version>
</Binary>
</Configuration>
</Data_List>
我正在使用C#代码,如下所示:
public Binary
{
public String Field;
public String Version;
}
public Configuration
{
public String Name;
public List<Binary> Binary_List = new List<Binary>();
public GetfromXML()
{
List<Configuration> lists = new List<Configuration>();
TextReader reader = new StreamReader("Data_List.config");
XmlSerializer serializer = new XmlSerializer(typeof(List<Configuration>));
lists=(List<Configuration>)serializer.Deserialize(reader);
reader.Close();
}
我得到一个例外,说“XML文档中存在错误(2,2)”。 任何人都可以帮忙吗?
答案 0 :(得分:3)
我认为问题在于你的模型没有很好的结构化。换句话说,序列化程序不知道如何读取.xml。
你的xml错了。如果你有List&lt; T>会有一个:
<ArrayOfT></ArrayOfT>
<。>在.XML中。这是你需要做的!
首先,尝试使用System.Xml.Serialization中的xml属性(即[XmlArray()])
最好使用FileStream而不是指出URI
using(var filestream = new FileStream(//your uri, FIleMode.Open)
{
}
我的代码示例我如何设法解决该问题:
public ServiceMap Deserialize()
{
ServiceMap serviceMap = new ServiceMap();
try
{
using (var fileStream = new FileStream(Settings.ServiceMapPath, FileMode.Open))
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
using (XmlReader reader = XmlReader.Create(fileStream, settings))
{
serviceMap = _serializer.Deserialize(reader) as ServiceMap;
}
}
}
catch (FileNotFoundException)
{
MessageBox.Show("File 'ServiceMap.xml' could not be found!");
}
return serviceMap;
}
我的ServiceMap类:
[XmlRoot("ServiceMap")]
public class ServiceMap
{
[XmlArray("Nodes")]
[XmlArrayItem("Node")]
public List<Node> Nodes = new List<Node>();
[XmlArray("Groups")]
[XmlArrayItem("Group")]
public List<Group> Groups = new List<Group>();
[XmlArray("Categories")]
[XmlArrayItem("Category")]
public List<Category> Categories = new List<Category>();
}
编辑:我的XML:
<?xml version="1.0" encoding="utf-8"?>
<ServiceMap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http:// www.w3.org/2001/XMLSchema">
<Nodes>
<Node Name="Predrag">
<Children>
<Child>dijete1</Child>
<Child>dijete2</Child>
<Child>dijete3</Child>
<Child>dijete4</Child>
</Children>
<Parents>
<Parent>roditelj1</Parent>
<Parent>roditelj2</Parent>
<Parent>roditelj3</Parent>
</Parents>
<Group Name="Grupa" />
<Category Name="Kategorija" />
</Node>
<Node Name="Tami">
<Children>
<Child>dijete1</Child>
<Child>dijete2</Child>
</Children>
<Parents>
<Parent>roditelj1</Parent>
</Parents>
<Group Name="Grupa2" />
<Category Name="Kategorija2" />
</Node>