【问题标题】:convert xml to sorted dictionary将xml转换为排序字典
【发布时间】:2009-03-17 09:37:13
【问题描述】:

我有一个类似这样的 xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <resource key="123">foo</resource>
    <resource key="456">bar</resource>
    <resource key="789">bar</resource>

</data>

我想把它作为键值对放入字典(排序)中。 IE: 123:富, 456:酒吧...等

密钥未知。

我该怎么做?

【问题讨论】:

    标签: c# xml


    【解决方案1】:

    这看起来像是 Linq to Xml 的工作

        static void Main(string[] args)
        {            
            XDocument yourDoc = XDocument.Load("the.xml");
            var q = from c in yourDoc.Descendants("resource")
                    orderby (int) c.Attribute("key")
                    select c.Attribute("key").Value + ":" + c.Value;
    
            foreach (string s in q)
                Console.WriteLine(s);                            
            Console.ReadLine();
        }
    

    【讨论】:

      【解决方案2】:

      试试这个,

      string s = "<data><resource key=\"123\">foo</resource><resource key=\"456\">bar</resource><resource key=\"789\">bar</resource></data>";
      XmlDocument xml = new XmlDocument();
      xml.LoadXml(s);
      XmlNodeList resources = xml.SelectNodes("data/resource");
      SortedDictionary<string,string> dictionary = new SortedDictionary<string,string>();
      foreach (XmlNode node in resources){
         dictionary.Add(node.Attributes["key"].Value, node.InnerText);
      }
      

      【讨论】:

      • 啊,伟大的思想都一样。我的版本更简洁一些,但方法是一样的。
      【解决方案3】:

      这实际上更容易不使用 Linq 而只使用 XmlDocument:

      SortedDictionary<string, string> myDict = new SortedDictionary<string, string>();
      foreach (XmlElement e in myXmlDocument.SelectNodes("/data/resource"))
      {
         myDict.Add(e.GetAttribute("key"), e.Value);
      }
      

      【讨论】:

        【解决方案4】:

        使用 LINQ:

        加载文档XDocument.LoadXDocument.Parse

        var xml = XDocument.Load(...);
        

        遍历有序序列:

        var sequence = from e in xml.Root.Elements() 
                       let key = (string)e.Attribute("key")
                       order by key
                       select new { 
                         Key = key, 
                         Value = (string)e 
                       };
        

        【讨论】:

          【解决方案5】:

          我会使用 XSLT 转换来做到这一点。你需要用 C# 来完成这项工作吗?如果不是,您可以简单地制作一个 XSLT 文档,该文档解析所有资源标签并为您整理输出 key:value。非常容易完成。这是您想要的解决方案吗?

          【讨论】:

          • 你如何处理转换输出?您仍然必须将其放入字典中。
          • 您可以随意输出。 HTML,TXT,由你决定。对吗?
          • 但没有任何形式的 XSLT 输出实现 IDictionary
          • 哦,我不知道有一个特殊的字典实现。 =)
          • @anakata 使用 XSLT 生成 C#(或任何其他语言)源代码很简单。因此,可以生成定义字典并向其中添加键值对的代码。 ChrisAD 是正确的,专门为树转换设计的最佳工具是 XSLT。
          猜你喜欢
          • 2016-08-17
          • 1970-01-01
          • 1970-01-01
          • 2021-03-28
          • 1970-01-01
          • 2012-12-06
          • 2010-12-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多