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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With