将 XML 反序列化为类 [英] Deserialize XML to Class
本文介绍了将 XML 反序列化为类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有正在反序列化的 XML,这是我的 XML
I have XML which I am de-serializing,This is my XML
<?xml version=\"1.0\" encoding=\"utf-16\"?>
<UserInfo xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<UserName>First_User</UserName>
<Age>25</Age>
</UserInfo>
我有这门课
namespace MyProject{
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http:/MyProject.ServiceContracts/2006/11", IsNullable = false)]
[DataContract]
public class UserInfo
{
private string username;
private string age;
[DataMember]
public string UserName
{
get
{
return this.username;
}
set
{
this.username = value;
}
}
[DataMember]
public string Age
{
get
{
return this.age;
}
set
{
this.age = value;
}
}
}
}
我正在这样做
XmlSerializer xmlSerSale = new XmlSerializer(typeof(UserInfo));
StringReader stringReader = new StringReader(myXML);
info = (UserInfo)xmlSerSale.Deserialize(stringReader);
stringReader.Close();
它给了我例外,
{"<UserInformation xmlns=''> was not expected."}
我该如何解决这个问题?还有其他解决方法吗?我必须在 WebService 中使用它
how can I fix this?Any alternate way to fix this? I have to use this in WebService
推荐答案
您在 xml 元描述符中声明命名空间:
You declare the namespace in your xml meta descriptors:
[XmlRoot(Namespace = "http:/MyProject.ServiceContracts/2006/11", IsNullable = false)]
public class UserInfo
{
[XmlElement]
public string UserName { get; set; }
[XmlElement]
public string Age { get; set; }
}
执行此操作时,您还必须在 xml 中具有此命名空间:
When you do this, you also have to have this namespace in your xml:
var foo = @"<?xml version=""1.0"" encoding=""utf-16""?>
<UserInfo xmlns='http:/MyProject.ServiceContracts/2006/11'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<UserName>First_User</UserName>
<Age>25</Age>
</UserInfo>";
var xmlSerSale = new XmlSerializer(typeof(UserInfo));
using (var stringReader = new StringReader(foo))
{
var info = (UserInfo)xmlSerSale.Deserialize(stringReader);
}
还要注意 [DataContract]
[DataMember]
属性被 XmlSerializer
忽略.
Also note the [DataContract]
[DataMember]
attributes are ignored by XmlSerializer
.
更新:如果您无法更改 xml,则必须从 XmlRoot
属性中删除命名空间描述符.即:
UPDATE: if you can't change the xml you have to drop the namespace descriptor from XmlRoot
attribute. I.E.:
[XmlRoot(IsNullable = false)]
public class UserInfo
{
[XmlElement]
public string UserName { get; set; }
[XmlElement]
public string Age { get; set; }
}
这篇关于将 XML 反序列化为类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文