xml文件的内容是:
<?xml version="1.0" encoding="utf-8" ?>
<Settings>
<username>test</username>
<password>test2</password>
</Settings>
我使用了visual studio自己的特殊粘贴来制作一个类:
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class Settings {
private object usernameField;
private object passwordField;
/// <remarks/>
public object username {
get {
return this.usernameField;
}
set {
this.usernameField = value;
}
}
/// <remarks/>
public object password {
get {
return this.passwordField;
}
set {
this.passwordField = value;
}
}
}
但现在当我尝试使用以下数据获取数据时:
s.password.ToString();
我得到的结果是:
System.Xml.XmlNode[]
而不是通缉:测试
我怎么能真正使用:
public object username {
get {
return this.usernameField;
}
set {
this.usernameField = value;
}
}
获取我认为正在放入的字符串。
EDIT !!!!
我实际上通过使用:
获得了价值XmlNode[] username = (XmlNode[]) s.username;
textBox1.Text = username[0].InnerText;
XmlNode[] password = (XmlNode[])s.password;
textBox2.Text = password[0].InnerText;
但是必须有更清洁的方法吗?
答案 0 :(得分:0)
只需将属性/字段声明为string
而不是object
:
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Settings {
private string usernameField;
private string passwordField;
/// <remarks/>
public string username
{
get
{
return this.usernameField;
}
set
{
this.usernameField = value;
}
}
/// <remarks/>
public string password
{
get
{
return this.passwordField;
}
set
{
this.passwordField = value;
}
}
}
.NET序列化不知道当成员被声明为object
时它应该期望什么类型的数据,所以它作为XmlNode
的数组进行反序列化的最一般选项。对象。