gpt4 book ai didi

xml - JSON.NET 和替换 @Sign in XML 到 JSON 的转换

转载 作者:数据小太阳 更新时间:2023-10-29 01:41:20 27 4
gpt4 key购买 nike

JSON.NET 框架可以将XML 转换为JSON,但它使用JSON 中的@ 符号作为属性。我宁愿在将它发送到 View 之前删除它。最好的方法是什么?

我知道我可以直接替换,但 @ 字符可能与某处相关,不应被替换。有正则表达式吗?

public ActionResult Layout()
{
var xml = new XmlDocument();
xml.XmlResolver = null;
xml.Load(Server.MapPath("~/App_Data/Navigation.xml"));
return Content(JsonConvert.SerializeXmlNode(xml, Newtonsoft.Json.Formatting.Indented));
}
{
"Layout": {
"Navigation": [
{
"@Type": "Menu",
"@Title": "Dashboard"
},
{
"@Type": "Menu",
"@Route": "Events",
"@Title": "Events",
"Navigation": {
"@Type": "Action",
"@Route": "Event",
"@Title": "+ Add Event",
"@Order": "1",
"Navigation": {
"@Type": "Item",
"@Route": "Event",
"@Name": "Event",
"Navigation": [
{
"@Route": "Pools",
"@Type": "SubNavigation",
"@Name": "Pools"
},
{
"@Route": "Brackets",
"@Type": "SubNavigation",
"@Name": "Brackets"
}
]
}
}
}
]
}
}

最佳答案

我花了很长时间才找到正确的答案,所以我想分享一下:

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);
}
}
}

输出:

{"xml":{"a":{"attr":"b","text":"c"}}}

关于xml - JSON.NET 和替换 @Sign in XML 到 JSON 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7278577/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com