C# суммировать несколько элементов в списке - PullRequest
0 голосов
/ 26 февраля 2020

Полагаю, мне просто нужна небольшая помощь, потому что я хожу по кругу с небольшой проблемой.

Это отчет с сервера развертывания, который хранит файлы в специальном формате xml.

Файл выглядит следующим образом:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<feed xml:base="XXXXX:9801/MDTMonitorData/" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
<title type="text">Computers</title>
<id>XXXXXXX:9801/MDTMonitorData/Computers/</id>
<updated>2020-02-26T06:49:07Z</updated>
<link rel="self" title="Computers" href="Computers" />
  <entry>
  <id>http://XXXXXXX:9801/MDTMonitorData/Computers(72)</id>
  <title type="text"></title>
  <updated>2020-02-26T07:24:45Z</updated>
  <author>
    <name />
  </author>
  <link rel="edit" title="Computer" href="Computers(72)" />
  <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/ComputerIdentities" type="application/atom+xml;type=feed" title="ComputerIdentities" href="Computers(72)/ComputerIdentities" />
  <category term="MDT_MonitorModel.Computer" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
  <content type="application/xml">
    <m:properties>
      <d:Name>NB-DE-00011</d:Name>
      <d:PercentComplete m:type="Edm.Int16">100</d:PercentComplete>
      <d:Settings m:null="true" />
      <d:Warnings m:type="Edm.Int32">0</d:Warnings>
      <d:Errors m:type="Edm.Int32">0</d:Errors>
      <d:DeploymentStatus m:type="Edm.Int32">3</d:DeploymentStatus>
      <d:StartTime m:type="Edm.DateTime">2020-02-25T07:33:15.797</d:StartTime>
      <d:EndTime m:type="Edm.DateTime">2020-02-25T08:02:26.653</d:EndTime>
      <d:ID m:type="Edm.Int32">72</d:ID>
      <d:UniqueID m:type="Edm.Guid">509c118c-3489-42c0-91ed-bf5695872a28</d:UniqueID>
      <d:CurrentStep m:type="Edm.Int32">91</d:CurrentStep>
      <d:TotalSteps m:type="Edm.Int32">91</d:TotalSteps>
      <d:StepName></d:StepName>
      <d:LastTime m:type="Edm.DateTime">2020-02-25T08:02:26.653</d:LastTime>
      <d:DartIP m:null="true" />
      <d:DartPort m:null="true" />
      <d:DartTicket m:null="true" />
      <d:VMHost m:null="true" />
      <d:VMName m:null="true" />
    </m:properties>
  </content>
</entry>
<entry>
  <id>http://XXXXXXX:9801/MDTMonitorData/Computers(71)</id>
  <title type="text"></title>
  <updated>2020-02-26T07:24:45Z</updated>
  <author>
    <name />
  </author>
  <link rel="edit" title="Computer" href="Computers(71)" />
  <link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/ComputerIdentities" type="application/atom+xml;type=feed" title="ComputerIdentities" href="Computers(71)/ComputerIdentities" />
  <category term="MDT_MonitorModel.Computer" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />
  <content type="application/xml">
    <m:properties>
      <d:Name>NB-DE-00210</d:Name>
      <d:PercentComplete m:type="Edm.Int16">100</d:PercentComplete>
      <d:Settings m:null="true" />
      <d:Warnings m:type="Edm.Int32">0</d:Warnings>
      <d:Errors m:type="Edm.Int32">0</d:Errors>
      <d:DeploymentStatus m:type="Edm.Int32">3</d:DeploymentStatus>
      <d:StartTime m:type="Edm.DateTime">2020-02-24T09:01:43.483</d:StartTime>
      <d:EndTime m:type="Edm.DateTime">2020-02-24T09:30:54.38</d:EndTime>
      <d:ID m:type="Edm.Int32">71</d:ID>
      <d:UniqueID m:type="Edm.Guid">0b3cff76-b983-4ac4-bc13-cd36c25318db</d:UniqueID>
      <d:CurrentStep m:type="Edm.Int32">91</d:CurrentStep>
      <d:TotalSteps m:type="Edm.Int32">91</d:TotalSteps>
      <d:StepName></d:StepName>
      <d:LastTime m:type="Edm.DateTime">2020-02-24T09:30:54.63</d:LastTime>
      <d:DartIP m:null="true" />
      <d:DartPort m:null="true" />
      <d:DartTicket m:null="true" />
      <d:VMHost m:null="true" />
      <d:VMName m:null="true" />
    </m:properties>
  </content>
</entry>

К сожалению, я не нашел разумного способа поместить все свойства каждой записи в список.

Пока что я создал класс с атрибутами, и теперь я хотел бы поместить это дерьмо в список.

Plan: давайте предположим, что список называется: mdtobject

MDTObject[0]:
Attr: Name | Value: NB-DE..
Attr:PercentComplete | Value 100

и так далее ..

Ответы [ 3 ]

0 голосов
/ 26 февраля 2020

Используйте xml linq и помещайте результаты в словарь:

using System;
using System.Collections.Generic;
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);
            XNamespace mNs = doc.Root.GetNamespaceOfPrefix("m");
            XNamespace dNs = doc.Root.GetNamespaceOfPrefix("d");

            Dictionary<string, string> dict = doc.Descendants(mNs + "properties").Elements()
                .GroupBy(x => x.Name.LocalName, y => (string)y)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        }
    }
}

для более чем одной записи используйте следующее:

            Dictionary<string, Dictionary<string, string>> dict2 = doc.Descendants(ns + "entry")
                .GroupBy(x => (string)x.Element(ns + "id"), y => y)
                .ToDictionary(x => x.Key, y => y.Descendants(mNs + "properties").FirstOrDefault().Elements()
                  .GroupBy(a => a.Name.LocalName, b => (string)b)
                  .ToDictionary(a => a.Key, b => b.FirstOrDefault()));
0 голосов
/ 26 февраля 2020

Это просто XML операция. Вы можете попробовать этот код.

public static List<Dictionary<string, object>> ParseXml(XDocument xd)
    {
        var namespaceM = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
        var namespaceD = "http://schemas.microsoft.com/ado/2007/08/dataservices";
        var ret = new List<Dictionary<string, object>>();
        var entryElements = xd.Descendants(XName.Get("entry", "http://www.w3.org/2005/Atom"));
        foreach (var entryElement in entryElements)
        {
            var propertiesElement = entryElement.Descendants(XName.Get("properties", namespaceM)).FirstOrDefault();
            if (propertiesElement != null)
            {
                var dict = new Dictionary<string, object>();
                var propertyElements = propertiesElement.Descendants();
                foreach (var propertyElement in propertyElements)
                {
                    var name = propertyElement.Name.LocalName;
                    var value = propertyElement.Value;
                    var typeAttr = propertyElement.Attribute(XName.Get("type", namespaceM));
                    var nullAttr = propertyElement.Attribute(XName.Get("null", namespaceM));
                    if (nullAttr != null && nullAttr.Value == "true")
                    {
                        dict.Add(name, null);
                    }
                    else if (typeAttr != null)
                    {
                        switch (typeAttr.Value)
                        {
                            case "Edm.Int16":
                                dict.Add(name, Convert.ToInt16(value));
                                break;
                            case "Edm.Int32":
                                dict.Add(name, Convert.ToInt32(value));
                                break;
                            case "Edm.DateTime":
                                dict.Add(name, Convert.ToDateTime(value));
                                break;
                            case "Edm.Guid":
                                dict.Add(name, Guid.Parse(value));
                                break;
                        }
                    }
                    else
                    {
                        dict.Add(name, value);
                    }
                }
                ret.Add(dict);
            }

        }
        return ret;
    }
0 голосов
/ 26 февраля 2020

In C#

var total = mdtobject.Sum (x => x. [УКАЗАТЬ НЕДВИЖИМОСТЬ ПУНКТА СПИСКА, КОТОРЫЕ БУДУТ ПОДГОТОВЛЕНЫ ЗДЕСЬ])

...