[英]How to get all attributes of childs element in an array from xdocument
I have xml in the following format我有以下格式的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>
Now i want to get all the attributes of PQR,XY and HIJ in a single array.现在我想在单个数组中获取 PQR、XY 和 HIJ 的所有属性。 Can anyone guide me how to get that?谁能指导我如何获得它?
I created a dictionary and fixed the xml我创建了一个字典并修复了 xml
Here is the 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>
Here is the code :这是代码:
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());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.