【问题标题】:Deserializing child elements in xml反序列化xml中的子元素
【发布时间】:2012-10-22 22:10:48
【问题描述】:

我应该如何让<site-standard-profile-request> 子元素正确反序列化,使其不显示为空?

反序列化过程完善;我只需要让子元素<site-standard-profile-request> 也进行序列化。

 //<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
    //- <person>
    //  <first-name>Storefront</first-name> 
    //  <last-name>Doors</last-name> 
    //  <headline>CEO at StorefrontDoors.NET</headline> 
    //- <site-standard-profile-request>
    //  <url>http://www.linkedin.com/profile?viewProfile=&key=147482099&authToken=-Igm&authType=name&trk=api*a216630*s224617*</url> 
    //  </site-standard-profile-request>
    //  </person>
    [XmlRoot("person")]
    [Serializable()]
    public class LinkedIn
    {
        [XmlElement("first-name")]
        public string FirstName { get; set; }
        [XmlElement("last-name")]
        public string LastName { get; set; }
        [XmlElement("headline")]
        public string Headline { get; set; }
        public string URL { get; set; }
    }


 string profile = oauth.APIWebRequest("GET", "https://api.linkedin.com/v1/people/~", null);
        //

        LinkedIn lkIn = null;

        BufferedStream stream = new BufferedStream(new MemoryStream());
        stream.Write(Encoding.ASCII.GetBytes(profile), 0, profile.Length);
        stream.Seek(0, SeekOrigin.Begin);
        StreamReader sr = new StreamReader(stream);
        XmlSerializer serializer = new XmlSerializer(typeof(LinkedIn));

        lkIn = (LinkedIn)serializer.Deserialize(sr);
        stream.Close();

【问题讨论】:

    标签: c# .net xml deserialization


    【解决方案1】:

    您将需要另一个仅将 url 作为属性的可序列化类。例如,

    [XmlRoot("site-standard-profile-request")]
    [Serializable()]
    public class StandardProfile
    {
        public string url { get;set;}
    }
    

    然后你现有的类应该使用它,比如

    [XmlRoot("person")]
    [Serializable()]
    public class LinkedIn
    {
        [XmlElement("first-name")]
        public string FirstName { get; set; }
        [XmlElement("last-name")]
        public string LastName { get; set; }
        [XmlElement("headline")]
        public string Headline { get; set; }
    
        public StandardProfile Profile { get;set; }
    }
    

    我没有测试过这段代码,但应该很接近。

    希望对您有所帮助。

    【讨论】:

    • 不知道为什么我在发布这个问题之前没有尝试这个。谢谢,效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多