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
This is my regex contribution, using lookaheads and lookbehinds to ensure it only occurs in the attribute field
(?m)(?<=^\s+\")(@)(?=.+\"\:)
Breakdown:
(?m) - Run in multiline mode
(?<=^\s+\") - Lookbehind to find the beginning of the line, one or more spaces, and a quote symbol
(@) - Match the @ after the quote
(?=.+\"\:) - Look ahead to match any character at least once, followed by another quote and then a colon
I went ahead and used this. Let me know if there is a better way.
public ActionResult Layout()
{
var xml = new XmlDocument();
xml.XmlResolver = null;
xml.Load(Server.MapPath("~/App_Data/Navigation.xml"));
var jsonText = JsonConvert.SerializeXmlNode(xml, Newtonsoft.Json.Formatting.Indented);
return Content(Regex.Replace(jsonText, "(?<=\")(@)(?!.*\":\\s )", string.Empty, RegexOptions.IgnoreCase));
}
The Regex not always work great,when content has the @ character and in the first place,that will be replace too.
so I think(?<!:)(\"@)(?!.\":\\s ) may be better.
First replace all "@" in your xml content with some placeholder (as example {{at_the_rate}}). Then use below code
JsonConvert.SerializeXmlNode(doc).Replace("@", "").Replace("{{at_the_rate}}", "@")
I suggest using the following regex, it the same as @yieio provided, but enhance to leave the content as is without any modifications, and affect only property names
var jString = Regex.Replace(
JsonConvert.SerializeXmlNode(content, Newtonsoft.Json.Formatting.None, true),
"(?<=(\\,\\\"|\\{\\\"))(@)(?!.*\\\":\\\\s )", String.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
It took me quite a while to find the right answer, so I thought I'd share:
var xDocument = XDocument.Parse("<xml><a attr=\"b\">c</a></xml>");
var builder = new StringBuilder();
JsonSerializer.Create().Serialize(new CustomJsonWriter(new StringWriter(builder)), xDocument);
var serialized = builder.ToString();
public class CustomJsonWriter : JsonTextWriter
{
public CustomJsonWriter(TextWriter writer): base(writer){}
public override void WritePropertyName(string name)
{
if (name.StartsWith("@") || name.StartsWith("#"))
{
base.WritePropertyName(name.Substring(1));
}
else
{
base.WritePropertyName(name);
}
}
}
Output:
{"xml":{"a":{"attr":"b","text":"c"}}}