【问题标题】:How to get all attributes of childs element in an array from xdocument如何从xdocument获取数组中子元素的所有属性
【发布时间】:2018-09-29 17:09:17
【问题描述】:

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

【问题讨论】:

    标签: c# xml linq-to-xml


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 2019-12-17
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多