-
Notifications
You must be signed in to change notification settings - Fork 1
/
LINQToXMLExample.cs
54 lines (46 loc) · 1.36 KB
/
LINQToXMLExample.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml.Linq;
// Example showing building XML and querying using LINQ to XML
namespace LINQToXMLExample
{
public class Program
{
static void Main()
{
var processes = QueryXML();
var pids = ParsePIDS(processes);
foreach(var pid in pids)
{
Console.WriteLine(pid);
}
}
private static IEnumerable<int> ParsePIDS(XDocument processes)
{
return processes
.Element("Processes")
.Elements("Process")
// OR: .Descendants("Process")
.Where(x => x.Attribute("Name").Value != "svchost")
.OrderBy(x => x.Attribute("Name").Value)
.Select(x => (int)x.Attribute("PID"));
}
private static XDocument QueryXML()
{
var processes = Process
.GetProcesses()
.Select(x =>
new XElement("Process",
new XAttribute("Name", x.ProcessName),
new XAttribute("PID", x.Id)
)
);
return new XDocument
(
new XElement("Processes", processes)
);
}
}
}