0

所以我有下面的函数,它接受一个字典并将它的存储到一个 XML 文件中。

static void DictionaryToXML(Dictionary<string,User> UserClassDict, string xmldoc)
        {

            Console.WriteLine("Moving User Dictionary data to XML (" + xmldoc + ")...");

            XElement el = new XElement("UserClassDictionary",
       UserClassDict.Select(kv => new XElement(kv.Key,
                    kv.Value.ControlNumber.Select(num => new XElement("ControlNumber", num)))));

            var xml = el.ToString();
            File.WriteAllText(xmldoc, xml);
        }

输出看起来像这样

    <?xml version="1.0"?>
        -<UserClassDictionary>-
<amsmith>
     <ControlNumber>1298136</ControlNumber>
</amsmith>
-<asnyder>
     <ControlNumber>1296234</ControlNumber>
</asnyder>
-<atreckey>
     <ControlNumber>1295885</ControlNumber>
</atreckey>

         </UserClassDictionary>

我需要帮助来重新格式化这个 XML。我希望格式看起来与此非常相似:

<UserClassDictionary>
  <User id="amsmith">
        <ControlNumbers>
            <ControlNumber> 111222 </ControlNumber>
        </ControlNumbers>
  </User>
  <User id="asnyder">
        <ControlNumbers>
            <ControlNumber> 222333 </ControlNumber>
            <ControlNumber> 222444 </ControlNumber>
        </ControlNumbers>
  </User>
4

1 回答 1

4

这将以您想要的格式生成 xml:

new XElement("UserClassDictionary",
      from kvp in UserClassDict
      select new XElement("User",
          new XAttribute("id", kvp.Key),
          new XElement("ControlNumbers",
               from cn in kvp.Value.ControlNumber
               select new XElement("ControlNumber", cn)
          )
      );
于 2013-06-14T22:10:33.267 回答