c# - resx 文件到 c# 中具有特定格式的 json
问题描述
我想以下面的 json 格式转换 resx 文件,你能帮我做同样的事情吗?
{
"TagText.p1":"Inspiration, Motivation",
"TagText.p2":"och utbildning för",
"TagText.p3":"ABO",
"TagText.p4":"globalt...",
"TagText.p5":"Var som helst / När som helst"
}
我试过下面的代码。var xml = File.ReadAllText(@"\Default.aspx.sv-SE.resx"); var obj = 新对象();
obj = new
{
Texts = XElement.Parse(xml)
.Elements("data")
.Select(el => new
{
Key = el.Attribute("name").Value,
Value = el.Element("value").Value.Trim(),
})
.ToList()
};
string json = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
解决方案
为了获得最佳效果,我认为您想将其放入字典中,然后将其序列化。我假设你的 xml 有一些父标签包含了它的全部内容:
using System;
using System.Xml.Linq;
using System.Linq;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var theXml = @"<myXml><data name=""About.h1"" xml:space=""preserve""> <value>Om</value> <comment>ABOUT</comment> </data> <data name=""AboutUs"" xml:space=""preserve""> <value>Om oss</value> <comment>ABOUT US</comment> </data></myXml>";
var obj = XElement.Parse(theXml)
.Elements("data")
.Select(el => new
{
Key = el.Attribute("name").Value,
Value = el.Element("value").Value.Trim(),
})
.ToDictionary(pair => pair.Key, pair => pair.Value);
string json = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
Console.Write(json);
}
}
输出:
{
"About.h1": "Om",
"AboutUs": "Om oss"
}
推荐阅读
- python - 在matplotlib中截断y轴
- reactjs - 使用 redux store 设置 React 组件的状态
- python-3.x - Python dict 更新是覆盖而不是追加
- python - Jupyter notebook 仅适用于基础环境
- c# - Unity 从 persistentDataPath 添加 mp3 文件
- reactjs - Firebase、React、高阶函数
- android - 如何确定上一个会话中的线程当前是否正在运行
- java - Keycloak:引用第三方库的自定义事件监听器
- java - Hibernate 如何使用 InheritanceType.JOINED 区分对象类型
- swift - 按下 tableViewCell 时将数据发送回之前的 View Controller