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



我有以下格式的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 的所有属性。 谁能指导我如何获得它?

我创建了一个字典并修复了 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:temptest.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());
}
}
}

最新更新