Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom XML output?

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?

like image 657
user1771591 Avatar asked Oct 24 '12 16:10

user1771591


1 Answers

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.

like image 132
Maggie Ying Avatar answered Oct 04 '22 16:10

Maggie Ying