簡體   English   中英

讀取XML數據並根據條件分類為列表

[英]Read XML data and sort into list based on conditions

嗨,這是我關於我要完成的一個小項目的第二個問題,第一個問題是基於將兩個文本文件中的某些數據匹配到一對要比較的列表中。 現在,我想對通過HTTP從一個寧靜的API收到的一些數據進行排序,以對第一個問題中的一個列表的列表進行對照。

這是文本文件的片段

C1903:009030           COMMERCIAL BREAK - 30 SE   0030COM
C1904:009040           COMMERCIAL BREAK - 40 SE   0040COM
C1918:009240           COMMERCIAL BREAK - 2 MIN   0240CO

這是XML數據的片段

<RCSZettaAPIResponse xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://rcsworks.com">
    <ResponseType>Success</ResponseType>
    <SyncCounter>1285121525</SyncCounter>
    <DataObject i:type="StationScheduleLog">
        <Date>2017-10-04T00:00:00</Date>
        <HourGroupCollection>
            <HourGroup>
                <Hour>19</Hour>
                <LogEventCollection>
                    <LogEvent>
                        <Chain>Segue</Chain>
                        <DisplayText>ExactTimeMarker - Reset : 00:00:00</DisplayText>
                        <ExactTimeMarkerEvent>
                            <Type>Reset</Type>
                        </ExactTimeMarkerEvent>
                        <StatusCode>Ready</StatusCode>
                        <Type>ExactTimeMarker</Type>
                        <UUID>d67afec1-59a3-e711-80ef-308d99b21a00</UUID>
                        <VerifyID></VerifyID>
                    </LogEvent>
                    <LogEvent>
                        <Chain>Stop</Chain>
                        <CommentEvent>
                            <Duration>PT3M</Duration>
                            <Text>Note: 3 Min Eagle News Bulletin</Text>
                        </CommentEvent>
                        <DisplayText>Comment - Note: 3 Min  News Bulletin</DisplayText>
                        <StatusCode>Ready</StatusCode>
                        <Type>Comment</Type>
                        <UUID>d77afec1-59a3-e711-80ef-308d99b21a00</UUID>
                        <VerifyID></VerifyID>
                    </LogEvent>
                    <LogEvent>
                        <Chain>Segue</Chain>
                        <DisplayText>ExactTimeMarker - Hit : 00:03:00</DisplayText>
                        <ExactTimeMarkerEvent>
                            <Time>PT3M</Time>
                            <Type>Hit</Type>
                        </ExactTimeMarkerEvent>
                        <StatusCode>Ready</StatusCode>
                        <Type>ExactTimeMarker</Type>
                        <UUID>d87afec1-59a3-e711-80ef-308d99b21a00</UUID>
                        <VerifyID></VerifyID>
                    </LogEvent>
                    <LogEvent>
                        <Chain>Segue</Chain>
                        <DisplayText>Spot Block</DisplayText>
                        <SpotBlockEvent>
                            <LogEventCollection>
                                <LogEvent>
                                    <AssetEvent>
                                        <EffectiveTransitions>
                                            <Duration>PT30.41S</Duration>
                                            <Runtime>PT30S</Runtime>
                                            <Segue>PT30S</Segue>
                                            <TrimIn>PT0S</TrimIn>
                                            <TrimOut>PT30.41S</TrimOut>
                                        </EffectiveTransitions>
                                        <Type>Spot</Type>
                                        <UUID>e2a39f0b-647b-4308-b85d-3f38affd2251</UUID>
                                    </AssetEvent>
                                    <Chain>Segue</Chain>
                                    <DisplayText>COMMERCIAL BREAK - 30 SEC ( 00:30.4 )</DisplayText>
                                    <EditCode>FlatFileInsert</EditCode>
                                    <StatusCode>Ready</StatusCode>
                                    <Type>Asset</Type>
                                    <UUID>ff4d423b-c79b-440c-bb98-e938871279dc</UUID>
                                    <VerifyID></VerifyID>
                                </LogEvent>
                            </LogEventCollection>
                            <OverrideSplitMode>Monitor</OverrideSplitMode>
                        </SpotBlockEvent>
                        <StatusCode>Ready</StatusCode>
                        <Type>SpotBlock</Type>
                        <UUID>d97afec1-59a3-e711-80ef-308d99b21a00</UUID>
                        <VerifyID></VerifyID>
                    </LogEvent>

我需要檢查日期標簽<Date>2017-10-04T00:00:00</Date> ,如果<Date>2017-10-04T00:00:00</Date>正確,請檢查日志文件C1903 (即7.03pm)與小時標簽<Hour>19</Hour>並在確切的時間標記處標記了小塊

                        <ExactTimeMarkerEvent>
                            <Time>PT3M</Time>
                            <Type>Hit</Type>
                        </ExactTimeMarkerEvent>

由確切時間標記中的PT3M數據表示,然后匹配中斷的長度0030COM (30秒)與<Type>SpotBlock</Type> xml中的xml <Runtime>PT30S</Runtime>中的中斷時間匹配。 <Type>SpotBlock</Type>元素。

如果這些不匹配,那么我需要通知用戶不匹配。

我遠遠超出了我的技能范圍,但是熱愛挑戰。 我只是不知道該怎么做,因此任何幫助指導將不勝感激

謝謝

西蒙

編輯加上jdweng的編輯

private void btnGetLog_Click(object sender, EventArgs e)
        {
            // client.Authenticator = new HttpBasicAuthenticator(username, password);
            var client = new RestClient("http://" + tbZettaAPIServer.Text + ":3139");

            var request = new RestRequest("1.0/{id}/{stuuid}/{date}?hourFrom={startHour}&hourTo={endHour}", Method.GET);
            //request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
            // replaces matching token in request.Resource
            request.AddUrlSegment("id", "StationScheduleLog"); // replaces matching token in request.Resource
            request.AddUrlSegment("stuuid", tbStationUUID.Text);
            request.AddUrlSegment("date", xmlDate);
            request.AddUrlSegment("startHour", "19");
            request.AddUrlSegment("endHour", "20");

            // adds to POST or URL querystring based on Method
            request.AddHeader("APIKEY", tbZettaAPIKey.Text);
            request.AddHeader("Accept", "application/xml");
            request.AddHeader("Content-Type", "application/xml");
            request.AddHeader("Authorization", "Basic " + zettaUsernameBase64);
            //request.AddHeader("Authorization", "Basic c3VwZXJ2aXNvcjo=");

            // replaces matching token in request.Resource
            //request.AddUrlSegment("id", "123"); 

            // easy async support
            client.ExecuteAsync(request, response => 
            {
                //tbXMLLog.Text = (response.Content);
                xmlResponce = (response.Content);

            });
            if (xmlResponce != null)
            {
                //XDocument zettaXML = XDocument.Parse(xmlResponce);
                XDocument zettaXML = XDocument.Parse(xmlResponce);
                XElement root = zettaXML.Root;
                XNamespace ns = root.GetDefaultNamespace();

                var results = root.Descendants(ns + "DataObject").Select(x => new {
                    date = (DateTime)x.Element(ns + "Date"),
                    hour = (int)x.Descendants(ns + "Hour").FirstOrDefault(),
                    time = (string)x.Descendants(ns + "Time").FirstOrDefault(),
                    runtime = (string)x.Descendants(ns + "Runtime").FirstOrDefault(),
                    displayText = x.Descendants(ns + "LogEvent").Where(y => (y.Element(ns + "AssetEvent") != null) && (y.Descendants(ns + "Runtime").Any())).Select(y => (string)y.Descendants(ns + "DisplayText").FirstOrDefault()).FirstOrDefault()
                }).ToList();


            }
        }

我在下面的代碼中使用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 URL = "https://pastebin.com/raw/Ch1BeS0k";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(URL);
            XElement root = doc.Root;
            XNamespace ns = root.GetDefaultNamespace();

            var results = root.Descendants(ns + "DataObject").Select(x => new
            {
                date = (DateTime)x.Element(ns + "Date"),
                hour = (int)x.Descendants(ns + "Hour").FirstOrDefault(),
                time = (string)x.Descendants(ns + "Time").FirstOrDefault(),
                runtime = (string)x.Descendants(ns + "Runtime").FirstOrDefault(),
                displayText = x.Descendants(ns + "LogEvent").Where(y => (y.Element(ns + "AssetEvent") != null) && (y.Descendants(ns + "Runtime").Any())).Select(y => (string)y.Descendants(ns + "DisplayText").FirstOrDefault()).FirstOrDefault()
            }).FirstOrDefault();
        }
    }
}

下面的代碼獲取所有日志事件


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

namespace ConsoleApplication1
{
    class Program
    {
        const string URL = "https://pastebin.com/raw/Ch1BeS0k";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(URL);
            XElement root = doc.Root;
            XNamespace ns = root.GetDefaultNamespace();

            var results = root.Descendants(ns + "DataObject").Select(dataObject => new
            {
                hourGroups = dataObject.Descendants(ns + "HourGroup").Select(hourGroup => new
                {
                    logEvents = hourGroup.Descendants(ns + "LogEvent").Select(logEvent => new
                    {
                        date = (DateTime)dataObject.Element(ns + "Date"),
                        hour = (int)hourGroup.Element(ns + "Hour"),
                        time = (string)logEvent.Descendants(ns + "Time").FirstOrDefault(),
                        runtime = (string)logEvent.Descendants(ns + "Runtime").FirstOrDefault(),
                        displayText = (logEvent.Element(ns + "AssetEvent") != null) && (logEvent.Descendants(ns + "Runtime").Any()) ? (string)logEvent.Descendants(ns + "DisplayText").FirstOrDefault() : string.Empty
                    }).ToList()
                }).SelectMany(x => x.logEvents)
            }).SelectMany(x => x.hourGroups).ToList();

            int minute = 0;
            string minutePattern = @"PT(?'minutes'\d+)M";
            string timespanPattern = @"\(\s*(?'timespan'[^\s]+)\s+\)";
            foreach (var result in results)
            {
                if (result.time != null)
                {
                    minute = int.Parse(Regex.Match(result.time, minutePattern).Groups["minutes"].Value);
                }
                if (result.displayText.Contains("COMMERCIAL BREAK"))
                {
                    string timeSpanStr = Regex.Match(result.displayText, timespanPattern).Groups["timespan"].Value;
                    DateTime timeSpan = DateTime.ParseExact(timeSpanStr, "mm:ss.f", CultureInfo.InvariantCulture);
                    Console.WriteLine("C{0}{1}:0{2}{3}       {4}", result.hour.ToString("00"), minute.ToString("00"), (result.hour % 12).ToString("00"),timeSpan.ToString("mmss"), result.displayText);
                }
            }
            Console.ReadLine();
        }
    }
}

樣品輸出

C1903:0070030       COMMERCIAL BREAK - 30 SEC ( 00:30.4 )
C1904:0070030       COMMERCIAL BREAK - 30 SEC ( 00:30.4 )
C1918:0070250       COMMERCIAL BREAK - 2 MIN 50 SEC ( 02:50.0 )
C1927:0070230       COMMERCIAL BREAK - 2 MIN 30 SEC ( 02:30.1 )
C1935:0070030       COMMERCIAL BREAK - 30 SEC ( 00:30.4 )
C1946:0070030       COMMERCIAL BREAK - 30 SEC ( 00:30.4 )
C1947:0070240       COMMERCIAL BREAK - 2 MIN 40 SEC ( 02:40.1 )
C1957:0070250       COMMERCIAL BREAK - 2 MIN 50 SEC ( 02:50.0 )
C2003:0080030       COMMERCIAL BREAK - 30 SEC ( 00:30.4 )
C2004:0080030       COMMERCIAL BREAK - 30 SEC ( 00:30.4 )
C2018:0080240       COMMERCIAL BREAK - 2 MIN 40 SEC ( 02:40.1 )
C2027:0080230       COMMERCIAL BREAK - 2 MIN 30 SEC ( 02:30.1 )
C2030:0080030       COMMERCIAL BREAK - 30 SEC ( 00:30.4 )
C2047:0080220       COMMERCIAL BREAK - 2 MIN 20 SEC ( 02:20.1 )
C2057:0080220       COMMERCIAL BREAK - 2 MIN 20 SEC ( 02:20.1 )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM