XML反序列化给出空值

时间:2012-06-03 11:43:18

标签: c# asp.net xml xml-serialization

我有一个像

这样的XML字符串
<?xml version="1.0"?>
<FullServiceAddressCorrectionDelivery xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <AuthenticationInfo xmlns="http://www.usps.com/postalone/services/UserAuthenticationSchema">
    <UserId xmlns="">FAPushService</UserId>
    <UserPassword xmlns="">Password4Now</UserPassword>
  </AuthenticationInfo>
</FullServiceAddressCorrectionDelivery>

为了使用Class映射节点,我有类似

的类结构
 [Serializable]
public class FullServiceAddressCorrectionDelivery
{
    [XmlElement("AuthenticationInfo")]
    public AuthenticationInfo AuthenticationInfo
    {
        get;
        set;
    }

}

[Serializable]
public class AuthenticationInfo 
{
    [XmlElement("UserId")]
    public string UserId
    {
        get;
        set;

    }
    [XmlElement("UserPassword")]
    public string UserPassword
    {
        get;
        set;

    }

}

对于反序列化,我使用xmlserializer来反序列化对象

        byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(xmlString);
        MemoryStream stream = new MemoryStream(byteArray);
        XmlSerializer xs = new XmlSerializer(typeof(FullServiceAddressCorrectionDelivery));
        var result = (FullServiceAddressCorrectionDelivery)xs.Deserialize(stream);

但值FullServiceAddressCorrectionDelivery对象始终为null。 请帮助我,我在这里做错了....

1 个答案:

答案 0 :(得分:0)

按照here

所述在XmlElement属性上添加命名空间
    [Serializable]
    public class FullServiceAddressCorrectionDelivery
    {
        [XmlElement("AuthenticationInfo", 
              Namespace = 
              "http://www.usps.com/postalone/services/UserAuthenticationSchema")]
        public AuthenticationInfo AuthenticationInfo
        {
            get;
            set;
        }
    }

    [Serializable]
    public class AuthenticationInfo
    {
        [XmlElement("UserId", Namespace="")]
        public string UserId
        {
            get;
            set;
        }
        [XmlElement("UserPassword", Namespace = "")]
        public string UserPassword
        {
            get;
            set;
        }
    }