[英]c# getting data from xml deserialized object
hey guys i ran into a little problem when i was trying to deserialize an xml file, 嗨,我在尝试反序列化xml文件时遇到了一个小问题,
the content of the xml file is: xml文件的内容为:
<?xml version="1.0" encoding="utf-8" ?>
<Settings>
<username>test</username>
<password>test2</password>
</Settings>
and i have used visual studio's own special paste to make a class out of this: 而且我已经使用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;
}
}
}
but now when i try to get the data using: 但是现在当我尝试使用以下方法获取数据时:
s.password.ToString();
the result i get is: 我得到的结果是:
System.Xml.XmlNode[]
instead of the wanted: Test 而不是通缉:测试
how can i actually use the : 我实际上如何使用:
public object username {
get {
return this.usernameField;
}
set {
this.usernameField = value;
}
}
to get the string returned that i think is being put inside. 得到我认为是放在里面的字符串返回。
EDIT!!!! 编辑!!!!
i actually got the values out by using: 我实际上是通过使用以下方法得出的:
XmlNode[] username = (XmlNode[]) s.username;
textBox1.Text = username[0].InnerText;
XmlNode[] password = (XmlNode[])s.password;
textBox2.Text = password[0].InnerText;
but there has to be a cleaner way of doing this? 但是必须有一种更清洁的方法吗?
Simply declare the properties/fields as string
rather than object
: 只需将属性/字段声明为
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 serialization doesn't know what type of data it should expect when the members are declared as object
, so it goes for the most general option of deserialization as an array of XmlNode
objects. .NET序列化不知道在将成员声明为
object
时应该期望什么样的数据类型,因此它适用于反序列化的最通用选项,即XmlNode
对象的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.