基于父节点和子节点的XML字典

时间:2017-01-15 07:49:11

标签: c# xml dictionary

我在WPF中编写了一个应用程序,我有以下XML:

<NewDataSet>
  <EYE>
    <DAD>Blue</DAD>
    <MOM>Brown</MOM>
  </EYE>
  <HAIR>
    <DAD>Black</DAD>
    <MOM>Brown</MOM>
  </HAIR>
  <SKIN>
    <DAD>White</DAD>
    <MOM>White</MOM>
  </SKIN>
</NewDataSet>

我想把XML读成字典,所以如果我选择阅读“DAD”数据,我会得到:

public Dictionary<string, string> values = new Dictionary<string, string>()
{
    {"EYE", Blue},
    {"HAIR", Black},
    {"SKIN", White}
};

是否可能,如果可以,我可以做谁? 任何代码片段都会非常有用。

2 个答案:

答案 0 :(得分:0)

这真的很简单:

    var xd = XDocument.Parse(@"<NewDataSet>
  <EYE>
    <DAD>Blue</DAD>
    <MOM>Brown</MOM>
  </EYE>
  <HAIR>
    <DAD>Black</DAD>
    <MOM>Brown</MOM>
  </HAIR>
  <SKIN>
    <DAD>White</DAD>
    <MOM>White</MOM>
  </SKIN>
</NewDataSet>");

Dictionary<string, string> values =
    xd
        .Root
        .Elements()
        .ToDictionary(
            xe => xe.Name.LocalName,
            xe => xe.Element("DAD").Value);

答案 1 :(得分:-1)

使用xml linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml =
                "<NewDataSet>" +
                    "<EYE>" +
                       "<DAD>Blue</DAD>" +
                       "<MOM>Brown</MOM>" +
                    "</EYE>" +
                    "<HAIR>" +
                       "<DAD>Black</DAD>" +
                       "<MOM>Brown</MOM>" +
                    "</HAIR>" +
                    "<SKIN>" +
                       "<DAD>White</DAD>" +
                       "<MOM>White</MOM>" +
                    "</SKIN>" +
                "</NewDataSet>";

            XElement dataset = XElement.Parse(xml);

            Dictionary<string, string> dadDict = dataset.Elements()
                .GroupBy(x => x.Name.LocalName, y => (string)y.Element("DAD"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
}