The JSON.NET framework can convert XML to JSON, but it uses the @ sign in the JSON as the attribute. I would rather remove this before sending it to the view. What would b
Another option is to create your own OneWayXmlNodeConverter inheriting from JsonConverter and call SerializeObject instead of SerializeXmlNode like this:
var json = JsonConvert.SerializeObject(xmlNode, new OneWayXmlNodeConverter());
I call it "One Way" because I assume the default XmlNodeConverter adds the "@" sign so it can convert back to XML from the resulting JSON.
If you include the JSON.NET source in your project (as opposed to just the compiled library), an easy way to create the OneWayXmlNodeConverter is to copy the XmlNodeConverter code, remove the hard-coded "@" sign in the private GetPropertyName method, and save it as OneWayXmlNodeConverter.
Note: I know that your question is specific to "replacing" the "@" sign, but the linked Preventing variation of this question is marked as duplicate.
If you want to access the value of an attribute because of the '@' sign, do the following:
Navigation["@Type"]
If the JSON is indented, this could work:
Regex.Replace(result, @"(\s*)""@(.*)"":", @"$1""$2"":", RegexOptions.IgnoreCase);
Has been a while since this response, but this may still help someone. Since you already have the XMLDocument, you can remove and convert the attributes before serializing it. I tried by either removing the attributes or converting them to elements.
public static void RemoveAllAttributes(XmlDocument xmlDocument)
{
if (xmlDocument == null || !xmlDocument.HasChildNodes) return;
foreach (var xmlElement in xmlDocument.SelectNodes(".//*").Cast<XmlElement>().Where(xmlElement => xmlElement.HasAttributes))
{
xmlElement.Attributes.RemoveAll();
}
}
public static void ElementifyAllAttributes(XmlDocument xmlDocument)
{
if (xmlDocument == null || !xmlDocument.HasChildNodes) return;
foreach (var xmlElement in xmlDocument.SelectNodes(".//*").Cast<XmlElement>().Where(xmlElement => xmlElement.HasAttributes))
{
foreach (XmlAttribute xmlAttribute in xmlElement.Attributes)
{
xmlElement.AppendChild(xmlDocument.CreateElement(xmlAttribute.Name)).InnerText = xmlAttribute.Value;
}
xmlElement.Attributes.RemoveAll();
}
}
And then;
private static string XmlToJson(XmlDocument xmlDocument)
{
if (xmlDocument == null) return null;
//Remove xml declaration
xmlDocument.RemoveChild(xmlDocument.FirstChild);
//Convert attributes to elements
ElementifyAllAttributes(xmlDocument);
return JsonConvert.SerializeXmlNode(xmlDocument, Formatting.None, false);
}