5

Playing around with the Web API with Framework 4.0 Wanted XML only output, so removed the JSON formatter from the formatters collection. Now, I'd like to modify the standard XML that the XMLSerializer is outputting:

<?xml version="1.0"?>
-<ArrayOfCategory xmlns:xsd="http://www.w3.org/2001/XMLSchema"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">-
  <Category>
    <Id>1</Id>
    <Name>Drink</Name>
  </Category>-
  <Category>
    <Id>2</Id>
    <Name>Snack</Name>
  </Category>
</ArrayOfCategory>

I'd like to change the "Arrayof" node to say something more meaningful, and need to add a couple more nodes (with extra information) above the "Arrayof" node.

Is there an easy way to do this? or do I have to write a custom formatter/seralizer?

tereško
  • 58,060
  • 25
  • 98
  • 150
user1771591
  • 87
  • 2
  • 9
  • Is this just not possible? Or am I missing something obvious? or is it so new, nobody knows of a solution yet? There's GOT to be a way to customize the default output. – user1771591 Oct 24 '12 at 18:31

1 Answers1

7

I'd like to change the "Arrayof" node to say something more meaningful, and need to add a couple more nodes (with extra information) above the "Arrayof" node.

If you want this kind of customization of your XML, you should use the the XmlSerializer instead of the DataContractSerializer that is used by default in the XmlFormatter.

config.Formatters.XmlFormatter.UseXmlSerializer = true;

Then, you can wrap your collection of Category into a class and use [XmlRoot], [XmlElement], and [XmlArray] to customize the element name. Here is an example:

[XmlRoot(ElementName = "node")]
public class Node
{
    [XmlElement(ElementName= "SomeInfo")]
    public string Node1;

    [XmlElement(ElementName = "OtherInfo")]
    public string Node2;

    [XmlArray("Categories")]
    public List<Category> CatList;
}

For more info, you can refer to this MSDN article: Controlling XML Serialization Using Attributes.

Maggie Ying
  • 10,095
  • 2
  • 33
  • 36
  • Thanks, Maggie. I had already switched to the XMLSerializer. Just now found an example to do this. But thanks for the response! – user1771591 Oct 24 '12 at 20:22