What I am trying to achieve is converting a JObject to XML Document and then extract the outer xml from the XMl Document. Reasons behind this is to send the results as a push notification through Azure Notification Hub.
What I am trying to get is:
<toast>
<visual>
<binding template="ToastGeneric">
<text id="1">Message</text>
</binding>
</visual>
</toast>
What I have tried:
JObject notificationPayload = new JObject(
new JProperty("toast",
new JObject(
new JProperty("visual",
new JObject(
new JProperty("binding",
new JObject(
new JProperty("@template", "ToastGeneric"),
new JProperty("text", notificationMessage,
new JProperty("@id", "1")))))))));
The above code is throwing an exception: Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray.
So what I have tried after is:
JObject notificationPayload = new JObject(
new JProperty("toast",
new JObject(
new JProperty("visual",
new JObject(
new JProperty("binding",
new JObject(
new JProperty("@template", "ToastGeneric"),
new JProperty("text", notificationMessage,
new JObject(
new JProperty("@id", "1"))))))))));
Above code gave me a result, but not the intended one. What I got was:
<toast>
<visual>
<binding template="ToastGeneric">
<text>Message</text>
<text id="1" />
</binding>
</visual>
</toast>
To extract Xml From the JObject I am using the following method:
string jsonStringToConvertToXmlString = JsonConvert.SerializeObject(notificationPayload);
XmlDocument doc = JsonConvert.DeserializeXmlNode(jsonStringToConvertToXmlString);
return doc.OuterXml;
Question: How could I give the id property to the same Text property?
Basically, don't use a tool oriented at JSON to construct XML. If you already had JSON, it would make sense to use Json.NET to convert it to XML - but as you're building it from scratch, it's much cleaner to use LINQ to XML:
XDocument doc = new XDocument(
new XElement("toast",
new XElement("visual",
new XElement("binding",
new XAttribute("template", "ToastGeneric"),
new XElement("text",
new XAttribute("id", 1),
"Message"
)
)
)
)
);
See more on this question at Stackoverflow