解析XML文件并使用值填充对象

时间:2011-08-28 18:42:28

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

在响应中发送带有所需参数的请求后,我得到以下XML:

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

我还做了以下两个课程:

[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; set; }
    public string IMGLINK { get; set; }
}

调试时我可以看到在响应中我得到了想要的结果。但是,我在解析XML并填充对象时遇到了麻烦。


调用方法:

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();
        }
    }

1 个答案:

答案 0 :(得分:0)

序列化程序区分大小写。您需要将属性content.Main重命名为main或将属性[XmlElement("main")]添加到其中。