If you have this string in C# directly, and you are not using a value, you need to de-serialize it first. JsonConvert uses Newtonsoft.Json.
string dataObj = "{\"Items\": [{\"id\":1},{\"id\":2}]}";
dynamic data = JsonConvert.DeserializeObject(dataObj );
Then, you can use the code from inside the webapi functions below to create your xml. Below is the code if you are passing this data to webapi in C#.
You can simply use a stringbuilder.
[Route("api/common/JsonToXml")]
[AcceptVerbs("POST")]
public HttpResponseMessage JsonToXml(dynamic data)
{
StringBuilder str = new StringBuilder();
str.Append("<Items>");
for (var ic = 0; ic < data.Items.Count; ic++)
{
str.Append("<element><id>");
str.Append(Convert.ToInt32(data.Items[ic].id));
str.Append("</id></element>");
}
str.Append("</Items>");
return Request.CreateResponse(HttpStatusCode.OK, Convert.ToString(str));
}
Or you can define your classes as below. Using Newtonsoft.Json, Serialize and Deserialize.
public class Items
{
public Items() {
this.element = new List<Element>();
}
public List<Element> element;
}
public class Element
{
public Element(int id) {
this.Id = id;
}
public int Id;
}
[Route("api/common/JsonToXml")]
[AcceptVerbs("POST")]
public HttpResponseMessage JsonToXml(dynamic data)
{
Items list = new Items();
list.element = new List<Element>();
for (var ic = 0; ic < data.Items.Count; ic++)
{
list.element.Add(new Element(Convert.ToInt32(data.Items[ic].id)));
}
XmlDocument xmlData = JsonConvert.DeserializeXmlNode(JsonConvert.SerializeObject(list), "Items");
return Request.CreateResponse(HttpStatusCode.OK, xmlData.OuterXml);
}