我尝试通过泛型(List<T>
)反序列化嵌套的XML。反序列化未嵌套的XML是可行的,但是嵌套的版本则不能。
XML:
<?xml version="1.0" encoding="utf-8"?>
<Users xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<User>
<UserId>1</UserId>
<LoginData>
<LoginName>Albert</LoginName>
<Password>albert</Password>
</LoginData>
<UserData>
<FirstName>Albert</FirstName>
<Surname>Einstein</Surname>
<BirthDate>2879-03-14T00:00:00</BirthDate>
<BirthPlace>German</BirthPlace>
<AddressCity>Württemberg</AddressCity>
</UserData>
</User>
</Users>
UserData.cs:
[Serializable]
public class MainData
{
public int UserId { get; set; }
public LoginData TestLoginData { get; set; }
public UserData TestUserData { get; set; }
}
public class LoginData
{
public string LoginName { get; set; }
public string Password { get; set; }
}
public class UserData
{
public string FirstName { get; set; }
public string Surname { get; set; }
public DateTime BirthDate { get; set; }
public string BirthPlace { get; set; }
public string AddressCity { get; set; }
}
反序列化:
public class XmlDataManager<T> : IDataManager<T>
where T : class
{
public List<T> Load(string pathAndName)
{
List<T> result = null;
StringReader stream = null;
XmlTextReader reader = null;
var xDocument = XDocument.Load(pathAndName);
string xml = xDocument.ToString();
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Users";
xRoot.IsNullable = true;
try
{
stream = new StringReader(xml);
reader = new XmlTextReader(stream);
result = new XmlSerializer(typeof(List<T>),
xRoot).Deserialize(reader) as List<T>;
}
catch (Exception ex)
{
Console.WriteLine(ex.GetBaseException());
}
return result;
}
// more code.....
}
}
User.cs的一部分:
[Serializable]
public class User : NotificationObject
{
MainData data;
public User()
{
data = new MainData();
}
//more code.....
public override string ToString()
{
return UserId + LoginName + Password + FirstName + Surname +
BirthDate + BirthPlace + AddressCity;
}
//more code.....
public int UserId
{
get { return data.UserId; }
set
{
NotifyPropertyChanging("UserId");
data.UserId = value;
NotifyPropertyChanged("UserId");
}
}
public string LoginName
{
get { return data.TestLoginData.LoginName; }
set
{
NotifyPropertyChanging("LoginName");
data.TestLoginData.LoginName = value;
NotifyPropertyChanged("LoginName");
}
}
.....
我不知道为什么要导入XML数据:
var xDocument = XDocument.Load(pathAndName);
string xml = xDocument.ToString();
但是反序列化给了我空值。怎么了?
答案 0 :(得分:0)
问题是您在类中的命名与xml中的命名不匹配。以下内容可以帮助您:
setCustomValidity('Please fill this field.')