将XML树转换为嵌套字典

本文关键字:嵌套 字典 转换 XML | 更新日期: 2023-09-27 18:20:58

我想将XML文件转换为Dictionary。XML文件的结构如下。

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Definitions>   
    <Organization ID="201">
        <Department Name="Facility">
            <Employees>200</Employees>
            <Building>3</Building>
            <Obj>classnameA</Obj>
        </Department>
        <Department Name="IT">
            <Employees>12</Employees>
            <Building>2</Building>
            <Obj>classnameB</Obj>
        </Department>
    </Organization> 
</Definitions>

我想使用一个嵌套的字典,它可以被概念化为一个表,这样"Department"是行号,"Organization"是列号,"Employees"、"Building"answers"Obj"是要在那里找到的值。因此,我创建了以下类(在这个线程的帮助下):

public class NestedDictionary<K1, K2, V> :
 Dictionary<K1, Dictionary<K2, V>> { }

然后,我需要通过遍历树将XML文件的内容转换为NestedDictionary。如何将"Employees"、"Building"answers"Obj"这三个属性添加到我的字典中?

private static void XmlToDict(XmlNode definitions)
{
    NestedDictionary<int, string, string> dictionary = new NestedDictionary<int, string, string>();
    foreach (XmlNode idNode in definitions)
    {
        foreach (XmlNode nameNode in idNode)
        {
            // The following line does not work
            dictionary.Add(idNode.Name, nameNode.Name, nameNode);
        }
    }
}

将XML树转换为嵌套字典

此LINQ表达式将把中的XML数据转换为嵌套字典。它假定element是来自System.Xml.Linq命名空间的类型XDocumentXElement

var element = XElement.Parse(yourXML);
var result = element.Descendants("Organization")
                .Select(org => new {
                    ID = org.Attribute("ID").Value,
                    Departments = org.Descendants("Department")
                    .Select(dept => new {
                        Name = dept.Attribute("Name").Value,
                        Employees = int.Parse(dept.Element("Employees").Value),
                        Building = dept.Element("Building").Value,
                        Obj = dept.Element("Obj").Value
                    })
                })
                .ToDictionary(
                    org => int.Parse(org.ID),
                    org => org.Departments.ToDictionary(dept => dept.Name));

结果成为CCD_ 5的字典。当然,如果您不希望使用匿名类型,您可以声明自己的Department类:

public class Department
{
    public int Building { get; set; }
    public int Employees { get; set; }
    public string Obj { get; set; }
}

并且调用CCD_ 7而不是如上所示的匿名CCD_。该表达式将生成<int, Dictionary<string, Department>> 类型的字典

不使用LINQ

    public class XmlConverter
    {
        public static Dictionary<int, Dictionary<string, Department>> Convert(XmlDocument xdoc)
        {
            Dictionary<int, Dictionary<string, Department>> result = new Dictionary<int, Dictionary<string, Department>>();
            foreach (XmlNode org in xdoc.SelectNodes("Definitions/Organization")) {
                int orgId = int.Parse(org.SelectSingleNode("@ID").Value);
                result.Add(orgId, GetDepartments(org));
            }
            return result;
        }
        private static Dictionary<string, Department> GetDepartments(XmlNode org)
        {
            Dictionary<string, Department> result = new Dictionary<string, Department>();
            foreach (XmlNode dept in org.SelectNodes("Department")) {
                string deptName = dept.SelectSingleNode("@Name").Value;
                Department d = new Department();
                d.Employees = int.Parse(dept.SelectSingleNode("Employees/text()").Value);
                d.Building = int.Parse(dept.SelectSingleNode("Building/text()").Value);
                d.Obj = dept.SelectSingleNode("Obj/text()").Value;
                result.Add(deptName, d);
            }
            return result;
        }
    }

我们将组织表示为Dictionary<string, Department>,其键是部门名称,值是部门对象。

整个树表示为Dictionary<int, Dictionary<string, Department>>,其键是组织ID,值是部门字典。

在Microsoft Visual Studio中使用粘贴XML作为C#类。您可以使用生成的类来描述您的字典、元组或您的需求,属性/对象的名称将与构建Xml is文件的名称完全相同。使用:

1. Visual Studio 2012 IDE you can convert XML document into C# classes as a Serializable type.

2. In .NET framework 4.5 there you have: Menu -> Edit -> Paste Special -> Paste Xml as Classes.

这个功能为我节省了很多工作,我之前使用过:

Xsd.exe可以在[InstallDrive]:''Program Files''Microsoft Visual Studio.NET[2003]''SDK[v1.1]''bin目录中找到。该实用工具的默认源输出语言是C#,生成XSD,并使用该XSD生成标准C#类,最后生成强类型DataSet。

打开命令提示符并键入xsd.exe/?查看该实用程序的所有命令和开关选项。

它是如何工作的?

Locate the Command Prompt from your version of visual studio:
1.    Check if xsd.exe exist (type xsd.exe) if true a list of commads will be displayed. 
2.    Navigate to your work folder.  (cd, cd..)
3.    Create your xml file MyFile.xml
4.    Run the transformation from xml to xsd with xsd.exe MyFile.xml
5.    Next create MyFile.cs wit command xsd.exe MyFile.xsd /c
In the folder is now created a file .cs with the C# class ready to read from xml.