我是 C# 的新手。我现在正在上一堂课,我们的一个类示例无法编译。Visual Studio 2010 给了我这个错误:XML 文档中存在错误 (3, 2)。
我应该如何编辑 XML 文件以使其与代码一起使用?
谢谢您的帮助!
public class SerializeIn
{
public static void Main()
{
// Declarations.
Person[] p = new Person[0];
string infile = "Persons.xml";
StreamReader sr = new StreamReader(infile);
XmlSerializer xs = new XmlSerializer(p.GetType());
// Deserialize Person object from disc.
p = (Person[])(xs.Deserialize(sr));
// Close StreamReader object to be safe.
sr.Close();
// Write what happened.
Console.WriteLine("Deserialized array p from output file " +
infile + ".");
// Print array.
foreach(Person x in p)
Console.WriteLine(x);
Console.ReadLine();
}
}
使用系统;namespace XmlArraySerialize { /// /// XmlArraySerialize 示例:序列化和反序列化 /// 一个 Person 数组。///
public class Person
{
public string name;
public string gender;
public int age;
// Noarg constructor needed for compatibility
public Person() { }
public Person(string theName, string theGender, int theAge)
{
name = theName;
gender = theGender;
age = theAge;
}
public override string ToString()
{
return name + " " + gender + " " + age;
}
}
}
和 XML 文件...
<?xml version="1.0" standalone="no"?>
<!--Created by ToXml Example in IO-->
<Persons>
<Person ID="1001">
<Name>Susan</Name>
<Gender>F</Gender>
<Age>21</Age>
</Person>
<Person ID="1002">
<Name>Michael</Name>
<Gender>M</Gender>
<Age>25</Age>
</Person>
<Person ID="1003">
<Name>Judy</Name>
<Gender>F</Gender>
<Age>31</Age>
</Person>
<Person ID="1004">
<Name>Chloe</Name>
<Gender>F</Gender>
<Age>27</Age>
</Person>
<Person ID="1005">
<Name>Scott</Name>
<Gender>M</Gender>
<Age>58</Age>
</Person>
<Person ID="1006">
<Name>William</Name>
<Gender>M</Gender>
<Age>41</Age>
</Person>
<Person ID="1007">
<Name>Mary</Name>
<Gender>F</Gender>
<Age>30</Age>
</Person>
</Persons>