首页 > 解决方案 > 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);

标签: c#json

解决方案


为了获得最佳效果,我认为您想将其放入字典中,然后将其序列。我假设你的 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"
}

见: https ://dotnetfiddle.net/fQuZZj


推荐阅读