且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从节点列表XML Xpath C#获取子节点的值

更新时间:2022-11-27 09:42:15

我使用XML Linq创建了一个嵌套字典:

I used XML Linq to create a nested dictionary :

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

namespace ConsoleApplication100
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            Dictionary<string, Dictionary<string, string>> dict = doc.Descendants("node")
                .GroupBy(x => (string)x.Attribute("id"), y => y.Elements("data")
                    .GroupBy(a => (string)a.Attribute("key"), b => (string)b)
                    .ToDictionary(a => a.Key, b => b.FirstOrDefault()))
                    .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        }
    }
}