我想反序列化一個XML文檔,但我使用的代碼每次都返回Null值。將XML反序列化爲對象返回空值
我有這樣
<?xml version="1.0" encoding="utf-8"?>
<RegistrationOpenData xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://example.gov">
<Description>Registration data is collected by ABC XYZ</Description>
<InformationURL>http://www.example.com/html/hpd/property-reg-unit.shtml</InformationURL>
<SourceAgency>ABC Department of Housing</SourceAgency>
<SourceSystem>PREMISYS</SourceSystem>
<StartDate>2016-02-29T00:03:06.642772-05:00</StartDate>
<EndDate i:nil="true" />
<Registrations>
<Registration xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<RegistrationID>108260</RegistrationID>
<BuildingID>4731</BuildingID>
</Registration>
</Registrations>
</RegistrationOpenData>
一個XML反序列化它,我創建了一個類
using System.Xml.Serialization;
using System.Xml;
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://example.gov")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://example.gov", IsNullable=true)]
public partial class Registration : InfoClass {
private long registrationIDField;
private bool registrationIDFieldSpecified;
private System.Nullable<long> buildingIDField;
private bool buildingIDFieldSpecified;
public long RegistrationID
{
get
{
return this.registrationIDField;
}
set
{
this.registrationIDField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool RegistrationIDSpecified {
get {
return this.registrationIDFieldSpecified;
}
set {
this.registrationIDFieldSpecified = value;
}
}
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
public System.Nullable<long> BuildingID {
get {
return this.buildingIDField;
}
set {
this.buildingIDField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool BuildingIDSpecified {
get {
return this.buildingIDFieldSpecified;
}
set {
this.buildingIDFieldSpecified = value;
}
}
和我使用的代碼
public void Test()
{
Registration RegistrationVal = null;
var xRoot = new XmlRootAttribute();
xRoot.ElementName = "RegistrationOpenData";
xRoot.Namespace = "http://services.hpd.gov";
xRoot.IsNullable = true;
var serializer = new XmlSerializer(typeof(Registration), xRoot);
using (TextReader reader = new StreamReader(@"D:\sample.xml"))
{
RegistrationVal = (Registration)serializer.Deserialize(reader);
}
}
這總是返回空值。 在此先感謝您的幫助。
調試時是否出現任何異常? –
不,我嘗試在TextBox中獲得RegistrationID的值,並且它打印0 – Hanumendra
「InfoClass」中的代碼是什麼?有沒有任何XML屬性? –