如何从xdocument获取数组中childs元素的所有属性

时间:2018-09-29 17:09:18

标签: c# xml linq-to-xml

我具有以下格式的xml

<ABC Attr1="1" Attr2="2">
   <PQR Attr1="1" Attr2="2" Attr="3">
   <XYZ Attr1="1" Attr2="2"></XYZ>
   <HIJ Attr1="1" Attr2="2"></HIJ>
   </PQR>
</ABC>

现在我想在单个数组中获取PQR,XY和HIJ的所有属性。     谁能指导我如何做到这一点?

1 个答案:

答案 0 :(得分:0)

我创建了字典并修复了XML

这是xml

<ABC Attr1="1" Attr2="2">
   <PQR Attr1="1" Attr2="2" Attr="3"/>
   <XYZ Attr1="1" Attr2="2"/>
   <HIJ Attr1="1" Attr2="2"/>
</ABC>

这是代码:

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XElement abc = doc.Root;

            Dictionary<string, Dictionary<string,string>> dict = abc.Elements()
                .GroupBy(x => x.Name.LocalName, y => y.Attributes()
                    .GroupBy(a => a.Name.LocalName, b => (string)b)
                    .ToDictionary(a => a.Key, b => b.FirstOrDefault()))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
}