【问题标题】:Reading XML dynamically using LINQ使用 LINQ 动态读取 XML
【发布时间】:2012-11-06 23:46:50
【问题描述】:
Document miXML = new XDocument(

            new XElement("Alumnos",
                                new XElement("Alumno",
                                    new XAttribute("NoControl", "05231104"),
                                    new XElement("Nombre", "Edison García")),


                                 new XElement("Alumno",
                                    new XAttribute("NoControl", "05231106"),
                                    new XElement("Nombre", "Abraham Gomez García"),
                                    new XElement("Semestre", "9")),

                                new XElement("Alumno",
                                    new XAttribute("NoControl", "05231108"),
                                    new XElement("Nombre", "Alejandre Carvajal"),
                                    new XElement("Semestre", "7")),

                                new XElement("Alumno",
                                    new XAttribute("NoControl", "06231110"),
                                    new XElement("Nombre", "Luis Armando"),
                                    new XElement("Semestre", "10"))
                   )
            );


        StringReader sr = new StringReader(miXML.ToString());
        var testlinq = XElement.Load(sr).Elements();

        foreach(var abc in testlinq){

        var test2 = from p in abc.Descendants("Nombre") select p;
        var test3 = from p in abc.Descendants("Semestre") select p;
        }

这是创建的 XML。

我想要一个字典列表 列表包括 {"Nombre","Edison Garcia"} , {{"Nombre", "Abraham Gomez García"} , {"semestre","9"}}

任何帮助将不胜感激。

我面临的问题: 1)如果没有 semsetre 我不能跳过它。它创建 IEnumerable。 2)动态获取节点和值而不是硬编码。例如: var test2 = from p in abc.Descendants("Nombre") select p;

【问题讨论】:

    标签: c# xml linq


    【解决方案1】:

    试试这个:

    var testlinq = XElement.Load(sr);   
    var test = testlinq.Descendants("Alumno")
                       .Select(x => x.Descendants()
                                     .ToDictionary(y => y.Name, y => y.Value )
                       ).ToList();
    

    【讨论】:

      猜你喜欢
      • 2012-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-08
      • 2012-10-13
      相关资源
      最近更新 更多