本地XML到c#中的Listbox
本文关键字:中的 Listbox XML 本地 | 更新日期: 2023-09-27 18:26:26
有一些类:
public class Student : INotifyPropertyChanged
{
string fullName;
string firstName;
string middleName;
string lastName;
string sex;
string photoFilename;
decimal gradePointAverage;
public string FullName
{
set
{
if (fullName != value)
{
fullName = value;
OnPropertyChanged("FullName");
}
}
get
{
return fullName;
}
}
...
protected virtual void OnPropertyChanged(string propChanged)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propChanged));
}
public event PropertyChangedEventHandler PropertyChanged;
}
和:
public class StudentBody : INotifyPropertyChanged
{
private string school;
ObservableCollection<Student> students = new ObservableCollection<Student>();
public string School
{
...
}
public ObservableCollection<Student> Students
{
set
{
if (students != value)
{
students = value;
}
}
get
{
return students;
}
}
private void NotifyPropertyChanged(string propertyName)
{
if (null != PropertyChanged)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
我正试着把学生的名字放在列表栏上:
ObservableCollection<StudentBody> StudentBody = new ObservableCollection<StudentBody>();
XmlSerializer serializer = new XmlSerializer(typeof(StudentBody));
XmlReader reader = XmlReader.Create(@"XMLFile1.xml");
StudentsList.ItemsSource = StudentBody;
来自tnis XML:
<?xml version="1.0" encoding="utf-8"?>
<StudentBody xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<School>El Paso High School</School>
<Students>
<Student>
<FullName>Adkins Bowden</FullName>
...
</Student>
<Student>
...
</Student>
<Student>
...
</Student>
</Students>
</StudentBody>
但最后我收到一个错误
找不到元素"StudentBody"的架构信息。
我做错了什么?如何将数据放入列表框?
编辑:
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var istream = new IsolatedStorageFileStream("XMLFile1.xml", FileMode.OpenOrCreate, store))
{
XmlSerializer xml = new XmlSerializer(typeof(StudentBody));
StudentBody StudentBody = xml.Deserialize(istream) as StudentBody; // here error
StudentsList.ItemsSource = StudentBody.Students;
}
}
错误:XML文档(0,0)中存在错误。
此处不需要使用XmlSerializer.Serialize和XmlSerializeer.Deserialize.XmlReader,这可能会导致问题。
此处的示例:http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx
编辑:
要打开文件,请使用FileStream类,并将其作为参数传递给这些方法。
引用以上链接:
FileStream fs = new FileStream(filename, FileMode.Open);
编辑2(关于评论):
抱歉,没有注意到WP7标签。我相信这里有一个关于你现在得到的例外的答案:
Windows Phone 7:FileStream异常