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.
精彩评论