c#从xml反序列化对象获取数据

时间:2015-02-27 23:09:50

标签: c# xml serialization xml-serialization

嘿伙计们,当我试图反序列化一个xml文件时遇到了一个小问题,

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;

但是必须有更清洁的方法吗?

1 个答案:

答案 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的数组进行反序列化的最一般选项。对象。