0

I am creating an API wrapper which gets an API response and converts it to POCO objects. Right now I have a test that follows this sequence of actions:

  • Create object with XML element names and values.
  • Serialize this object to XML format.
  • Convert the XML tree back to an actual object trough my converter.
  • Assert if the values inside my new object are as expected.

I have the following helper class which represents a show object:

class TestShow {
 public string id { get; set; }
 public string IMDB_ID { get; set; }
 public string Language { get; set; }
}

The serializer:

var serializer = new XmlSerializer(show.GetType());
string xml;

using (var writer = new StringWriter()) {
   serializer.Serialize(writer, show);
   xml = writer.ToString();
}

However, when I serialize this to XML I get this result:

<?xml version="1.0" encoding="utf-16"?>
<TestShow xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <id>76290</id>
  <IMDB_ID>tt0285331</IMDB_ID>
  <Language>en</Language>
</TestShow>

The desired result is this:

<Data>
 <Series>
  <id>76290</id>
  <IMDB_ID>tt0285331</IMDB_ID>
  <Language>en</Language>
 </Series>
</Data>

This shows two issues:

  1. The name of TestShow should be changed to Series. Is there an easy way to do this, or should I just change my class name?
  2. There is an upper collection called Data. How would I add this?
3
  • What serialiser are you using? Commented Sep 14, 2013 at 12:52
  • @SamLeach: I've added the serializer. It's the standard XmlSerializer. Commented Sep 14, 2013 at 12:54
  • Use attributes, see my answer below. Commented Sep 14, 2013 at 13:00

1 Answer 1

3

Add Xml attributes to the POCO:

class TestShow 
{
    public string id { get; set; }
    public string IMDB_ID { get; set; }
    public string Language { get; set; }
}

[XmlRoot("Data")]
class Data 
{
    [XmlElement("Series")]
    public TestShow TestShow { get; set; }
}
Sign up to request clarification or add additional context in comments.

2 Comments

The XmlElement tag throws an error: Attribute 'XmlElement' is not valid on this declaration type. It is only valid on 'property, indexer, field, param, return' declarations. Are you sure it can be placed as a class tag?
@JeroenVannevel: No, it should be moved to adorn the public TestShow TestShow { get; set; } line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.