【问题标题】:resx file to json with specific format in c#resx 文件到 c# 中具有特定格式的 json
【发布时间】:2021-05-16 04:10:12
【问题描述】:

我想将 resx 文件转换成下面的 json 格式,你能帮我做同样的事情吗?

{
"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 = new Object();

        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吗?在尝试序列化之前obj 的内容是什么?
  • @Jonathan 请找到以下代码 OmABOUT data> Om oss关于我们

标签: c# json


【解决方案1】:

为了最好的结果,我想你想把它放入字典中,然后序列化那个。我假设你的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-06
    • 2016-03-24
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2021-02-28
    相关资源
    最近更新 更多