简体   繁体   English

如何将Xml(从XLSX文件)序列化为Json? C#.NET Json.Net

[英]How to serialize Xml (from XLSX files) to Json ? C# .NET Json.Net

I'm processing different kind of Xlsx files. 我正在处理不同类型的Xlsx文件。
These files have multiples possibility of column eg 2 or 6 or even 7 Columns) 这些文件具有列的倍数,例如2或6或甚至7列
I read the Xml data inside using OpenXml and i would like to generate Json files from each worksheet. 我使用OpenXml读取里面的Xml数据,我想从每个工作表生成Json文件。
Actually i'm able to read and to iterate through every worksheet but it seems weird when i try to convert it into Json format using Newtonsoft.Json 实际上我能够阅读并遍历每个工作表但是当我尝试使用Newtonsoft.Json将其转换为Json格式时,这似乎很奇怪


The Excel files is similare to this Excel文件类似于此
Item 1 || 第1项|| Item 2 || 第2项|| Item 3 第3项
V1 || V1 || V2 || V2 || V3 V3
V1 || V1 || V2 || V2 || V3 V3
V1 || V1 || V2 || V2 || V3 V3

But the generated JSON file is similare to this 但生成的JSON文件与此类似
[ [
[Item 1 ,Item 2 ,Item 3] [第1项,第2项,第3项]
[V1 ,V2 ,V3] [V1,V2,V3]
[V1 ,V2 ,V3] [V1,V2,V3]
[V1 ,V2 ,V3] [V1,V2,V3]
] ]


And i would like to format it like this 我想像这样格式化它


{ {
{"Item 1":"V1" ,"Item 2":"V2" ,"Item 3":"V3"} {“第1项”:“V1”,“第2项”:“V2”,“第3项”:“V3”}
{"Item 1":"V1" ,"Item 2":"V2" ,"Item 3":"V3"} {“第1项”:“V1”,“第2项”:“V2”,“第3项”:“V3”}
{"Item 1":"V1" ,"Item 2":"V2" ,"Item 3":"V3"} {“第1项”:“V1”,“第2项”:“V2”,“第3项”:“V3”}
} }

Here is my code : 这是我的代码:

using (SpreadsheetDocument excelDocument = SpreadsheetDocument.Open(file, false)) { var documentBody = excelDocument.WorkbookPart.Workbook; using(SpreadsheetDocument excelDocument = SpreadsheetDocument.Open(file,false)){var documentBody = excelDocument.WorkbookPart.Workbook;

            var sheets = documentBody.Sheets.Cast<Sheet>().ToList();
            sheets.ForEach(x => Console.WriteLine(String.Format("RelationshipId:{0}\n SheetName:{1}\n SheetId:{2}", x.Id.Value, x.Name.Value, x.SheetId.Value)));

            SharedStringTablePart sstpart = excelDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
            SharedStringTable sst = sstpart.SharedStringTable;

            Console.WriteLine("Worksheet count = {0}", documentBody.WorkbookPart.WorksheetParts.Count());

            foreach (var worksheetPart in documentBody.WorkbookPart.WorksheetParts)
            {

                DocumentFormat.OpenXml.Spreadsheet.Worksheet sheet = worksheetPart.Worksheet;

                var cells = sheet.Descendants<Cell>();
                var rows = sheet.Descendants<Row>();

                Console.WriteLine("Row count = {0}", rows.LongCount());
                Console.WriteLine("Cell count = {0}", cells.LongCount());
                var list = new List<string[]>();
                foreach (Row row in rows)
                {
                    Console.WriteLine("Row number: {0}", row.RowIndex);
                    list.Add(row.Elements<Cell>().Select(x => x.InnerText).ToArray());
                    foreach (Cell c in row.Elements<Cell>())
                    {
                        if (c.CellValue != null)
                        {
                            Console.WriteLine("Cell contents: {0}", c.CellValue.Text);

                        }
                    }
                }
                var i = JsonConvert.SerializeObject(list, Newtonsoft.Json.Formatting.Indented);


            }
        }

In your case I recommend to use List of ExpandoObject instead of List of string[]. 在您的情况下,我建议使用List of ExpandoObject而不是List of string []。 It's a dynamic object generated as a IDictionnary 它是作为IDictionnary生成的动态对象

var list = new List<ExpandoObject>();
var expandoObject = new ExpandoObject();
var dict = (IDictionary<string, Object>)expandoObject;
dict.Add("NewProp", "prop value");
dict.Add("SecondProp", 58);
list.add(expandoObject);

To convert an XML node contained in string xml into a JSON string 将字符串xml中包含的XML节点转换为JSON字符串

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

To convert JSON text contained in string json into an XML node 将字符串json中包含的JSON文本转换为XML节点

 XmlDocument doc = JsonConvert.DeserializeXmlNode(json);

Documentation here: Click Here for Documentation 文档: 点击此处查看文档

OR Try this below Code there i have used dictionary 或者尝试下面的代码,我使用过字典

class Program
{
static void Main()
{
    var xml = 
    @"<Columns>
      <Column Name=""key1"" DataType=""Boolean"">True</Column>
      <Column Name=""key2"" DataType=""String"">Hello World</Column>
      <Column Name=""key3"" DataType=""Integer"">999</Column>
    </Columns>";
    var dic = XDocument
        .Parse(xml)
        .Descendants("Column")
        .ToDictionary(
            c => c.Attribute("Name").Value, 
            c => c.Value
        );
    var json = new JavaScriptSerializer().Serialize(dic);
    Console.WriteLine(json);
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM