开发者

Parse XML file and populate object with values

After I send a request with the required parameters in the response I get the following XML:

<content>
    <main>
        <IMGURL>image url</IMGURL>
        <IMGTEXT>Click Here</IMGTEXT>
        <TITLE>image title</TITLE>
        <IMGLINK>image link</IMGLINK>
    </main>
</content>

and I also made the following two classes:

[Serializable]
public class content
{
    private Main _main;
    public content()
    {
        _main = new Main();
    }
    public Main Main
    {
        get { return _main; }
        set { _main = value; }
    }
}

[Serializable]
public class Main
{
    public string IMGURL { get; set; }
    public string IMGTEXT { get; set; }
    public string TITLE { get; se开发者_运维知识库t; }
    public string IMGLINK { get; set; }
}

While debugging I can see that in the response I get the wanted results. However I'm having troubles deserializing the XML and populating the object.


Call to the method:

public static class ImageDetails
    {
        private static string _url = ConfigurationManager.AppSettings["GetImageUrl"];

        public static content GetImageDetails(string ua)
        {
            var contenta = new content();
            _url += "&ua=" + ua;
            try
            {
                WebRequest req = WebRequest.Create(_url);
                var resp = req.GetResponse();
                var stream = resp.GetResponseStream();

                //var streamreader = new StreamReader(stream);

                //var content = streamreader.ReadToEnd();



                var xs = new XmlSerializer(typeof(content));
                if (stream != null)
                {
                    contenta = (content)xs.Deserialize(stream);
                    return contenta;
                }
            }
            catch (Exception ex)
            {
            }
            return new content();
        }
    }


The serializer is case-sensitive. You either need to rename the property content.Main to main or add the attribute [XmlElement("main")] to it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜