1

I'm working on a project that makes use of the ImgUr.com API I request an image, or an album, and the XML is returned.

I'm using a Serializer to Deserialize the XML back into an object. So I made classes for both Image and Album.

But here comes the tricky part... An album looks something like this:

<data success="1" result="200">
  <id>x</id>
  ...
  <images>
    <item>
      <id>x</id>
      <link>http://linktoimage.jpg</link>
      ...
    </item>
    <item>
      <id>x</id>
      <link>http://linktoimage.jpg</link>
      ...
    </item>
    ...
  </images>
</data>

So the root-element of the actual image is 'item'.

But when I request the actual image through the API, i get the following:

<data success="1" result="200">
  <id>x</id>
  <link>http://linktoimage.jpg</link>
  ...
</data>

Now, the root element is 'data'.

So the solution I have now is two different classes. One with [XMLRootElement(Elementname = "item")] and one with [XMLRootElement(Elementname = "data")] but I guess there should be a simplere solution to this?

Edit: By request of Henk, my receiving-part The code I have for recieving the XML:

var request = WebRequest.Create(String.Format("{0}image/{1}.xml",     Settings.Default.ImgUrBaseUrl, albumId));
request.Headers.Add("Authorization", "Client-ID " + Settings.Default.ImgUrClientID);

var response = request.GetResponse();
var imageStream = response.GetResponseStream();
if (imageStream == null) return "";
var serilizer = new XmlSerializer(typeof(ImgUrSingleImage));
var result = serilizer.Deserialize(imageStream) as ImgUrSingleImage;

So, I guess I need to take out the <data> tag, and wrap the remaining xml in a new <item> tag?

4

1 回答 1

1

您可以像这样插入<image>标签:

var imageStream = response.GetResponseStream();
if (imageStream == null) return "";

XElement doc = XElement.Load(imageStream);            
XElement item = new XElement("item", doc.Elements());
doc.ReplaceNodes(item);
var reader = new StringReader(doc.ToString());

var serilizer = new XmlSerializer(typeof(ImgUrSingleImage));
var result = serilizer.Deserialize(reader) as ImgUrSingleImage;

然后你的ImgUrSingleImage类应该有一个Item与列表请求相同的属性。

或者,您可以跳过<data>标记并直接从itemXElement 反序列化。

于 2013-08-01T08:12:41.783 回答