C# 多层级xml转字典

前言

xml对象在做很多解析的时候会比较复杂,可以转成字典进行操作


二、转换成字典

这个方法可以适用用多层级xml结构生成字典

 public static Dictionary<string, object> CreateDict(Dictionary<string, object> dict, XmlNode root)
        {
            if (root.HasChildNodes && root.ChildNodes[0].Name != "#text")
            {
               
                foreach (XmlNode node in root.ChildNodes)
                {
                    if (node.NodeType == XmlNodeType.Element)
                    {
                        if (node.HasChildNodes && node.ChildNodes[0].Name != "#text")
                        {
                            CreateDict(dict, node);
                        }
                        else
                        {
                            dict[node.Name] = node.InnerText;
                        }
                    }
                }
            }
            return dict;
        }

调用实例:

    static void Main(string[] args)
      {
          string xml = @""1.0"" encoding=""UTF-8"" standalone=""yes""?>SUCCESS好发唱歌二保焊肝1111120026T11111200290.011200144653462562016-08-22 12:12:007897 JsLUv6BdWdFPgXfDApgwzRmzulkng1wkv3rstb2z0Gy/cgx4jJZSGqZZ9fZIYxnJ2SSjhJs8AdLLmqucRSNoLlkAtSW71QX4pKAlplmeJ5GPaa0pk3VP5odWjBQn2Uww+G4uBAeLUXzZTkqUNTbMrGNM8e9ZGBGgWuzIeCJ301s= RSA-S2020-12-02 09:31:19";
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);
            Dictionary<string, object> xmlDict = new Dictionary<string, object>();
            XmlNode root = xmlDoc.DocumentElement;
            if (root.HasChildNodes)
            {
                CreateDict(xmlDict, root);
            }
      }

最终效果可以将全部的xml节点都转换成字典格式。

你可能感兴趣的:(C#,c#,xml,java)