XML To Dictionary

本文关键字:Dictionary To XML | 更新日期: 2023-09-27 18:17:28

我希望下面的函数读取XML文件并将所有数据保存到传递给函数的UserClassDict中。UserClassDict保存a(用户名,用户类)。用户类有一个属性List<int> ControlNumber,它存储ControlNumbers.

它试图读取的XML看起来像这样:

<UserClassDictionary>
   <adolan>
      <ControlNumber>791301</ControlNumber>
   </adolan>
   <afeazell>
      <ControlNumber>790253</ControlNumber>
   </afeazell>
   <asnyder>
      <ControlNumber>790210</ControlNumber>
      <ControlNumber>790308</ControlNumber>
   </asnyder>
   <semery/>
   <showard/>
   <talexander/>
</UserClassDictionary>

我遇到的问题是函数中的LINQ似乎无法区分不同的xml节点。它似乎没有将节点设置为Key而将节点设置为Value。

 static void XMLToDictionary(Dictionary<string,User> UserClassDict)
        {
        XmlDocument doc = new XmlDocument();
        doc.Load("UserClassDictionary.xml");
        StringWriter sw = new StringWriter();
        XmlTextWriter tx = new XmlTextWriter(sw);
        doc.WriteTo(tx);
        string str = sw.ToString();
        XDocument document = XDocument.Parse(str);
            foreach (XElement element in document.Descendants().Where(p => p.HasElements == false))
        {
            int keyInt = 0;
            string keyName = element.Name.LocalName;
            while (UserClassDict.ContainsKey(keyName))
                keyName = element.Name.LocalName + "_" + keyInt++;
            UserClassDict.Add(keyName, element.Value);
        }
        }

XML To Dictionary

首先,您不需要StreamWriterXmlTextWriter。你可以用XElement.Load()代替。

XElement root = XElement.Load("UserClassDictionary.xml");
Dictionary<string, List<string>> values = new Dictionary<string, List<string>>();
foreach(XElement subNode in root.Elements().Where(x => x.Elements().Count() > 0))
{
    values.Add(subNode.Name.LocalName, subNode.Elements("ControlNumber")
        .Select(x => x.Value).ToList());
}

你的另一个原因是你在循环中使用Descendents而不是Elements。它查找xml中的每个子节点,甚至是子节点。

您可以使用Linq to xml解析xml并创建用户字典:

XDocument xdoc = XDocument.Load("UserClassDictionary.xml");
Dictionary<string, User> users = 
     xdoc.Root.Elements()
         .Select(u => new User {
             Name = u.Name.LocalName,
             ControlNumber = u.Elements().Select(cn => (int)cn).ToList()
          })
         .Where(u => ControlNumber.Any())
         .ToDictionary(u => u.Name);

或者如果您希望更新现有的字典

var users = from u in xdoc.Root.Elements()
            where u.Elements().Any()
            select new User {
                 Name = u.Name.LocalName,
                 ControlNumber = u.Elements().Select(cn => (int)cn).ToList()
             };
foreach(var user in users)
     UserClassDict.Add(user.Name, user);