/
LinqToXmlSamples.cs
executable file
·1970 lines (1751 loc) · 85.4 KB
/
LinqToXmlSamples.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright © Microsoft Corporation. All Rights Reserved.
// This code released under the terms of the
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
//
//Copyright (C) Microsoft Corporation. All rights reserved.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using SampleSupport;
using System.Xml;
using System.Text.RegularExpressions;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
// new comment added
namespace SampleQueries {
[Title("101+ Linq To Xml Query Samples")]
[Prefix("XLinq")]
public class LinqToXmlSamples : SampleHarness {
public string dataPath = Path.GetFullPath(Path.Combine(Application.StartupPath, @"..\..\Data\"));
[Category("Load")]
[Title("Load document from file")]
[Description("Load an XML document from a file")]
public void XLinq1() {
XDocument doc = XDocument.Load(dataPath + "bib.xml");
Console.WriteLine(doc);
}
[Category("Load")]
[Title("Load document from string")]
[Description("Load document from string")]
public void XLinq2() {
string xml = "<book price='100' isbn='1002310'>" +
"<title>XClarity Samples</title>" +
"<author>Matt</author>" +
"</book>";
XDocument doc = XDocument.Parse(xml);
Console.WriteLine(doc);
}
//load an XML document from XmlReader
[Category("Load")]
[Title("Load document from XmlReader")]
[Description("Load an XML document from XmlReader")]
public void XLinq3() {
XmlReader reader = XmlReader.Create(dataPath + "bib.xml");
XDocument doc = XDocument.Load(reader);
Console.WriteLine(doc);
}
[Category("Load")]
[Title("Element from XmlReader - 1")]
[Description("Construct XElement from XmlReader positioned on an element")]
public void XLinq4() {
XmlReader reader = XmlReader.Create(dataPath + "nw_customers.xml");
reader.Read();//move to root
reader.Read(); // move to fist customer
XElement c = (XElement)XNode.ReadFrom(reader);
Console.WriteLine(c);
}
[Category("Load")]
[Title("Element from XmlReader - 2")]
[Description("Read XElement content from XmlReader")]
public void XLinq5() {
XmlReader reader = XmlReader.Create(dataPath + "config.xml");
//the file has comments and whitespace at the start
reader.Read();
reader.Read();
XElement config = new XElement("appSettings",
"This content will be replaced");
config.RemoveAll();
while (!reader.EOF)
config.Add(XNode.ReadFrom(reader));
Console.WriteLine(config);
}
[Category("Construction")]
[Title("Construct an XElement from string")]
[Description("Construct an XElement from string")]
public void XLinq6() {
string xml = "<purchaseOrder price='100'>" +
"<item price='50'>Motor</item>" +
"<item price='50'>Cable</item>" +
"</purchaseOrder>";
XElement po = XElement.Parse(xml);
Console.WriteLine(po);
}
[Category("Construction")]
[Title("Add XML declaration to a document")]
[Description("Add XML declaration to a document")]
public void XLinq7() {
XDocument doc = new XDocument(new XDeclaration("1.0", "UTF-16", "Yes"),
new XElement("foo"));
StringWriter sw = new StringWriter();
doc.Save(sw);
Console.WriteLine(sw);
}
[Category("Construction")]
[Title("Computed element name")]
[Description("Computed element name")]
public void XLinq8() {
XDocument customers = XDocument.Load(dataPath + "nw_customers.xml");
string name = (string)customers.Elements("Root")
.Elements("Customers")
.First()
.Attribute("CustomerID");
XElement result = new XElement(name,
"Element with a computed name");
Console.WriteLine(result);
}
[Category("Construction")]
[Title("Document creation")]
[Description("Create a simple config file")]
public void XLinq9() {
XDocument myDocument =
new XDocument(
new XElement("configuration",
new XElement("system.web",
new XElement("membership",
new XElement("providers",
new XElement("add",
new XAttribute("name",
"WebAdminMembershipProvider"),
new XAttribute("type",
"System.Web.Administration.WebAdminMembershipProvider")))),
new XElement("httpModules",
new XElement("add",
new XAttribute("name",
"WebAdminModule"),
new XAttribute("type",
"System.Web.Administration.WebAdminModule"))),
new XElement("authentication",
new XAttribute("mode", "Windows")),
new XElement("authorization",
new XElement("deny",
new XAttribute("users", "?"))),
new XElement("identity",
new XAttribute("impersonate", "true")),
new XElement("trust",
new XAttribute("level", "full")),
new XElement("pages",
new XAttribute("validationRequest", "true")))));
Console.WriteLine(myDocument);
}
// <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
// xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
// <xsd:element name="root" sql:is-constant="1">
// <xsd:complexType>
// <xsd:sequence>
// <xsd:element name="Customers" minOccurs="100" maxOccurs="unbounded">
// <xsd:complexType>
// <xsd:sequence>
// <xsd:element name="CompanyName" type="xsd:string" />
// <xsd:element name="ContactName" type="xsd:string" />
// <xsd:element name="ContactTitle" type="xsd:string" />
// <xsd:element name="Phone" type="xsd:string" />
// <xsd:element name="Fax" type="xsd:string"/>
// <xsd:element ref="FullAddress" maxOccurs="3"/>
// <xsd:element name="Date" type="xsd:date"/>
// </xsd:sequence>
// <xsd:attribute name="CustomerID" type="xsd:integer" />
// </xsd:complexType>
// </xsd:element>
// </xsd:sequence>
// </xsd:complexType>
// </xsd:element>
// <xsd:element name="FullAddress" sql:relation="Customers" sql:relationship="CustAdd" sql:key-fields="CustomerID" >
// <xsd:complexType>
// <xsd:sequence>
// <xsd:element name="Address" type="xsd:string" />
// <xsd:element name="City" type="xsd:string" />
// <xsd:element name="Region" type="xsd:string" />
// <xsd:element name="PostalCode" type="xsd:string" />
// <xsd:element name="Country" type="xsd:string" />
// </xsd:sequence>
// </xsd:complexType>
// </xsd:element>
//</xsd:schema>
[Category("Construction")]
[Title("Create an XmlSchema")]
[Description("Create an XmlSchema")]
public void XLinq10() {
XNamespace XSD = "http://www.w3.org/2001/XMLSchema";
XNamespace SQL = "urn:schemas-microsoft-com:mapping-schema";
XElement result =
new XElement(XSD + "schema",
new XAttribute(XNamespace.Xmlns + "xsd", "http://www.w3.org/2001/XMLSchema"),
new XAttribute(XNamespace.Xmlns + "sql", "urn:schemas-microsoft-com:mapping-schema"),
new XElement(XSD + "element",
new XAttribute("name", "root"),
new XAttribute(SQL + "is-constant", "1"),
new XElement(XSD + "complexType",
new XElement(XSD + "sequence",
new XElement(XSD + "element",
new XAttribute("name", "Customers"),
new XAttribute("minOccurs", "100"),
new XAttribute("maxOccurs", "unbounded"),
new XElement(XSD + "complexType",
new XElement(XSD + "sequence",
new XElement(XSD + "element",
new XAttribute("name", "CompanyName"),
new XAttribute("type", "xsd:string")),
new XElement(XSD + "element",
new XAttribute("name", "ContactName"),
new XAttribute("type", "xsd:string")),
new XElement(XSD + "element",
new XAttribute("name", "ContactTitle"),
new XAttribute("type", "xsd:string")),
new XElement(XSD + "element",
new XAttribute("name", "Phone"),
new XAttribute("type", "xsd:string")),
new XElement(XSD + "element",
new XAttribute("name", "Fax"),
new XAttribute("type", "xsd:string")),
new XElement(XSD + "element",
new XAttribute("ref", "FullAddress"),
new XAttribute("maxOccurs", "3")),
new XElement(XSD + "element",
new XAttribute("name", "Date"),
new XAttribute("type", "xsd:date"))),
new XElement(XSD + "attribute",
new XAttribute("name", "CustomerID"),
new XAttribute("type", "xsd:integer"))))))),
new XElement(XSD + "element",
new XAttribute("name", "FullAddress"),
new XAttribute(SQL + "relation", "Customers"),
new XAttribute(SQL + "relationship", "CustAdd"),
new XAttribute(SQL + "key-fields", "CustomerID"),
new XElement(XSD + "complexType",
new XElement(XSD + "sequence",
new XElement(XSD + "element",
new XAttribute("name", "Address"),
new XAttribute("type", "xsd:string")),
new XElement(XSD + "element",
new XAttribute("name", "City"),
new XAttribute("type", "xsd:string")),
new XElement(XSD + "element",
new XAttribute("name", "Region"),
new XAttribute("type", "xsd:string")),
new XElement(XSD + "element",
new XAttribute("name", "PostalCode"),
new XAttribute("type", "xsd:string")),
new XElement(XSD + "element",
new XAttribute("name", "Country"),
new XAttribute("type", "xsd:string"))))));
Console.WriteLine(result);
}
[Category("Construction")]
[Title("Construct a PI")]
[Description("Create an XML document with an XSLT PI")]
public void XLinq11() {
XDocument result = new XDocument(
new XProcessingInstruction("xml-stylesheet",
"type='text/xsl' href='diff.xsl'"),
new XElement("foo"));
Console.WriteLine(result);
}
[Category("Construction")]
[Title("XML comment construction")]
[Description("XML comment construction")]
public void XLinq12() {
XDocument result =
new XDocument(
new XComment("My phone book"),
new XElement("phoneBook",
new XComment("My friends"),
new XElement("Contact",
new XAttribute("name", "Ralph"),
new XElement("homephone", "425-234-4567"),
new XElement("cellphone", "206-345-75656")),
new XElement("Contact",
new XAttribute("name", "Dave"),
new XElement("homephone", "516-756-9454"),
new XElement("cellphone", "516-762-1546")),
new XComment("My family"),
new XElement("Contact",
new XAttribute("name", "Julia"),
new XElement("homephone", "425-578-1053"),
new XElement("cellphone", "")),
new XComment("My team"),
new XElement("Contact",
new XAttribute("name", "Robert"),
new XElement("homephone", "345-565-1653"),
new XElement("cellphone", "321-456-2567"))));
Console.WriteLine(result);
}
[Category("Construction")]
[Title("Create a CData section")]
[Description("Create a CData section")]
public void XLinq13() {
XElement e = new XElement("Dump",
new XCData("<dump>this is some xml</dump>"),
new XText("some other text"));
Console.WriteLine("Element Value: {0}", e.Value);
Console.WriteLine("Text nodes collapsed!: {0}", e.Nodes().First());
Console.WriteLine("CData preserved on serialization: {0}", e);
}
[Category("Construction")]
[Title("Create a sequence of nodes")]
[Description("Create a sequence of customer elements")]
public void XLinq14() {
var cSequence = new[] {
new XElement("customer",
new XAttribute("id","x"),"new customer"),
new XElement("customer",
new XAttribute("id","y"),"new customer"),
new XElement("customer",
new XAttribute("id","z"),"new customer")};
foreach (var c in cSequence)
Console.WriteLine(c);
}
[Category("Write")]
[Title("Write an XElement to XmlWriter")]
[Description("Write an XElement to XmlWriter using the WriteTo method")]
public void XLinq15() {
XElement po1 = new XElement("PurchaseOrder",
new XElement("Item", "Motor",
new XAttribute("price", "100")));
XElement po2 = new XElement("PurchaseOrder",
new XElement("Item", "Cable",
new XAttribute("price", "10")));
XElement po3 = new XElement("PurchaseOrder",
new XElement("Item", "Switch",
new XAttribute("price", "10")));
StringWriter sw = new StringWriter();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter w = XmlWriter.Create(sw, settings);
w.WriteStartElement("PurchaseOrders");
po1.WriteTo(w);
po2.WriteTo(w);
po3.WriteTo(w);
w.WriteEndElement();
w.Close();
Console.WriteLine(sw.ToString());
}
[Category("Write")]
[Title("Write the content of an XDocument to XmlWriter")]
[Description("Write the content of XDocument to XmlWriter using the WriteTo method")]
public void XLinq16() {
XDocument doc1 = new XDocument(
new XElement("PurchaseOrders",
new XElement("PurchaseOrder",
new XElement("Item", "Motor",
new XAttribute("price", "100"))),
new XElement("PurchaseOrder",
new XElement("Item", "Cable",
new XAttribute("price", "10")))));
XDocument doc2 = new XDocument(
new XElement("PurchaseOrders",
new XElement("PurchaseOrder",
new XElement("Item", "Switch",
new XAttribute("price", "10")))));
StringWriter sw = new StringWriter();
XmlWriter w = XmlWriter.Create(sw);
w.WriteStartDocument();
w.WriteStartElement("AllPurchaseOrders");
doc1.Root.WriteTo(w);
doc2.Root.WriteTo(w);
w.WriteEndElement();
w.WriteEndDocument();
w.Close();
Console.WriteLine(sw.ToString());
}
[Category("Write")]
[Title("Save XDocument")]
[Description("Save XDocument using XmlWriter/TextWriter/File")]
public void XLinq17() {
XDocument doc = new XDocument(
new XElement("PurchaseOrders",
new XElement("PurchaseOrder",
new XElement("Item",
"Motor",
new XAttribute("price", "100"))),
new XElement("PurchaseOrder",
new XElement("Item",
"Switch",
new XAttribute("price", "10"))),
new XElement("PurchaseOrder",
new XElement("Item",
"Cable",
new XAttribute("price", "10")))));
StringWriter sw = new StringWriter();
//save to XmlWriter
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter w = XmlWriter.Create(sw, settings);
doc.Save(w);
w.Close();
Console.WriteLine(sw.ToString());
//save to file
doc.Save("out.xml");
}
[Category("Query")]
[Title("Query for child elements")]
[Description("Select all the customers in the xml document")]
public void XLinq18() {
XDocument doc = XDocument.Load(dataPath + "nw_customers.xml");
foreach (XElement result in doc.Elements("Root")
.Elements("Customers"))
Console.WriteLine(result);
}
[Category("Query")]
[Title("Query for all child elements")]
[Description("Select all the child elements of the first customer")]
public void XLinq19() {
XDocument doc = XDocument.Load(dataPath + "nw_customers.xml");
var query = doc.Element("Root")
.Element("Customers")
.Elements();
foreach (XElement result in query)
Console.WriteLine(result);
}
[Category("Query")]
[Title("Query for first child element - 1")]
[Description("Select the first customer in the document")]
public void XLinq20() {
XDocument doc = XDocument.Load(dataPath + "nw_customers.xml");
var result = doc.Element("Root")
.Element("Customers");
Console.WriteLine(result);
}
[Category("Query")]
[Title("Query for first child element - 2")]
[Description("Query for one child element on a sequence of elements")]
public void XLinq21() {
XDocument doc = XDocument.Load(dataPath + "nw_customers.xml");
var result = doc.Elements()
.Elements("Customers")
.First()
.Element("CompanyName");
Console.WriteLine(result);
}
[Category("Query")]
[Title("Query for attributes")]
[Description("Selects all the CustomerIDs in the xml document")]
public void XLinq22() {
XDocument doc = XDocument.Load(dataPath + "nw_customers.xml");
var query = doc.Element("Root")
.Elements("Customers")
.Attributes("CustomerID");
foreach (XAttribute result in query)
Console.WriteLine(result.Name + " = " + result.Value);
}
[Category("Query")]
[Title("Cast an attribute to a number")]
[Description("Find orders with price > 100")]
public void XLinq23() {
string xml = "<order >" +
"<item price='150'>Motor</item>" +
"<item price='50'>Cable</item>" +
"<item price='50'>Modem</item>" +
"<item price='250'>Monitor</item>" +
"<item price='10'>Mouse</item>" +
"</order>";
XElement order = XElement.Parse(xml);
var query =
from
i in order.Elements("item")
where
(int)i.Attribute("price") > 100
select i;
foreach (var result in query)
Console.WriteLine("Expensive Item {0} costs {1}",
(string)result,
(string)result.Attribute("price"));
}
[Category("Query")]
[Title("Get the root element of a document")]
[Description("Get the root element of a document")]
public void XLinq24() {
XElement root = XDocument.Load(dataPath + "config.xml")
.Root;
Console.WriteLine("Name of root element is {0}", root.Name);
}
[Category("Query")]
[Title("Filter query results using where")]
[Description("Filter query results using where")]
public void XLinq25() {
XDocument doc = XDocument.Load(dataPath + "nw_customers.xml");
var query =
from
c in doc.Element("Root")
.Elements("Customers")
where
c.Element("FullAddress")
.Element("Country")
.Value == "Germany"
select c;
foreach (XElement result in query)
Console.WriteLine(result);
}
[Category("Query")]
[Title("Select all descendants of an element")]
[Description("Select all ContactName elements in the document")]
public void XLinq26() {
XDocument doc = XDocument.Load(dataPath + "nw_customers.xml");
var query = doc.Descendants("ContactName");
foreach (XElement result in query)
Console.WriteLine(result);
}
[Category("Query")]
[Title("Select all descendants of a given type")]
[Description("Select all text in the document")]
public void XLinq27() {
XDocument doc = XDocument.Load(dataPath + "nw_customers.xml");
var query = doc.DescendantNodes().OfType<XText>().Select(t => t.Value);
foreach (string result in query)
Console.WriteLine(result);
}
[Category("Query")]
[Title("Select all ancestors")]
[Description("Check if two nodes belong to the same document")]
public void XLinq28() {
XDocument doc = XDocument.Load(dataPath + "nw_customers.xml");
XElement element1 = doc.Element("Root");
XElement element2 = doc.Descendants("Customers")
.ElementAt(3);
var query = from a in element1.AncestorsAndSelf()
from b in element2.AncestorsAndSelf()
where a == b
select a;
Console.WriteLine(query.Any());
}
[Category("Query")]
[Title("Query for parent")]
[Description("Query for parent of an Element")]
public void XLinq29() {
XElement item = new XElement("item-01",
"Computer");
XElement order = new XElement("order", item);
XElement p = item.Parent;
Console.WriteLine(p.Name);
}
[Category("Query")]
[Title("Join over two sequences")]
[Description("Add customer company info to orders of the first customer")]
public void XLinq30() {
XDocument customers = XDocument.Load(dataPath + "nw_customers.xml");
XDocument orders = XDocument.Load(dataPath + "nw_orders.xml");
var query =
from customer in customers.Descendants("Customers").Take(1)
join order in orders.Descendants("Orders")
on (string)customer.Attribute("CustomerID") equals
(string)order.Element("CustomerID")
select
new XElement("Order",
order.Nodes(),
customer.Element("CompanyName"));
foreach (var result in query)
Console.WriteLine(result);
}
[Category("Query")]
[Title("Query content of a type")]
[Description("Query content of a given type of an existing element")]
public void XLinq31() {
XElement elem =
new XElement("customer",
new XElement("name",
"jack"),
"some text",
new XComment("new customer"),
new XAttribute("id",
"abc"));
//string content
foreach (XText s in elem.Nodes().OfType<XText>())
Console.WriteLine("String content: {0}", s);
//element content
foreach (XElement e in elem.Elements())
Console.WriteLine("Element content: {0}", e);
//comment content
foreach (XComment c in elem.Nodes().OfType<XComment>())
Console.WriteLine("Comment content: {0}", c);
}
[Category("Query")]
[Title("Query using XStreamingElement")]
[Description("Query for all Swedish customer orders and Swedish orders whose freight is > 250")]
[LinkedMethod("GetSwedishFreightProfile")]
[LinkedMethod("GetSwedishCustomerOrders")]
[LinkedMethod("AddNewOrder")]
public void XLinq32() {
XDocument customers = XDocument.Load(dataPath + "nw_customers.xml");
XDocument orders = XDocument.Load(dataPath + "nw_orders.xml");
XStreamingElement summary = new XStreamingElement("Summary",
new XAttribute("Country", "Sweden"),
new XStreamingElement("SwedishCustomerOrders", GetSwedishCustomerOrders(customers, orders)),
new XStreamingElement("Orders", GetSwedishFreightProfile(orders)));
Console.WriteLine(summary);
//DML operation, which adds a new order for customer BERGS freight > 250
AddNewOrder(orders);
Console.WriteLine("****XStreaming Output after DML reflects new order added!!****");
Console.WriteLine(summary);
}
static void AddNewOrder(XDocument orders) {
string order = @"<Orders>
<CustomerID>BERGS</CustomerID>
<ShipInfo ShippedDate='1997-12-09T00:00:00'>
<Freight>301</Freight>
<ShipCountry>Sweden</ShipCountry>
</ShipInfo>
</Orders>";
XElement newOrder = XElement.Parse(order);
orders.Root.Add(newOrder);
}
private static IEnumerable<XElement> GetSwedishFreightProfile(XDocument orders) {
return
from
order in orders.Descendants("Orders")
where
(string)order.Element("ShipInfo").Element("ShipCountry") == "Sweden"
&& (float)order.Element("ShipInfo").Element("Freight") > 250
select
new XElement("Order",
new XAttribute("Freight",
(string)order.Element("ShipInfo").Element("Freight")));
}
private static IEnumerable<XElement> GetSwedishCustomerOrders(XDocument customers, XDocument orders) {
return
from
customer in customers.Descendants("Customers")
where
(string)customer.Element("FullAddress").Element("Country") == "Sweden"
select
new XElement("Customer",
new XAttribute("Name",
(string)customer.Element("CompanyName")),
new XAttribute("OrderCount",
(from
order in orders.Descendants("Orders")
where
(string)order.Element("CustomerID") == (string)customer.Attribute("CustomerID")
select
order).Count()));
}
[Category("Query")]
[Title("Positional predicate")]
[Description("Query the 3rd customer in the document")]
public void XLinq33() {
XDocument doc = XDocument.Load(dataPath + "nw_customers.xml");
var c = doc.Descendants("Customers")
.ElementAt(2);
Console.WriteLine(c);
}
[Category("Query")]
[Title("Union two sequences of nodes")]
[Description("Union books authored by two authors: Serge and Peter")]
public void XLinq34() {
XDocument doc = XDocument.Load(dataPath + "bib.xml");
var b1 = doc.Descendants("book")
.Where(b => b.Elements("author")
.Elements("first")
.Any(f => (string)f == "Serge"));
var b2 = doc.Descendants("book")
.Where(b => b.Elements("author")
.Elements("first")
.Any(f => (string)f == "Peter"));
var books = b1.Union(b2);
foreach (var b in books)
Console.WriteLine(b);
}
[Category("Query")]
[Title("Intersect two sequences of nodes")]
[Description("Intersect books that are common for both authors")]
public void XLinq35() {
XDocument doc = XDocument.Load(dataPath + "bib.xml");
var b1 = doc.Descendants("book")
.Where(b => b.Elements("author")
.Elements("first")
.Any(f => (string)f == "Serge"));
var b2 = doc.Descendants("book")
.Where(b => b.Elements("author")
.Elements("first")
.Any(f => (string)f == "Peter"));
var books = b1.Intersect(b2);
foreach (var b in books)
Console.WriteLine(b);
}
[Category("Query")]
[Title("All nodes in sequence 1 except the nodes in sequence 2")]
[Description("Find books that are authored by Peter and did not have Serge as co-author")]
public void XLinq36() {
XDocument doc = XDocument.Load(dataPath + "bib.xml");
var b1 = doc.Descendants("book")
.Where(b => b.Elements("author")
.Elements("first")
.Any(f => (string)f == "Serge"));
var b2 = doc.Descendants("book")
.Where(b => b.Elements("author")
.Elements("first")
.Any(f => (string)f == "Peter"));
var books = b2.Except(b1);
foreach (var b in books)
Console.WriteLine(b);
}
[Category("Query")]
[Title("Reverse the order of nodes in a sequence")]
[Description("Display the path to a node")]
[LinkedMethod("PrintPath")]
public void XLinq37() {
XDocument doc = XDocument.Load(dataPath + "bib.xml");
XElement e = doc.Descendants("last")
.First();
PrintPath(e);
}
static void PrintPath(XElement e) {
var nodes = e.AncestorsAndSelf()
.Reverse();
foreach (var n in nodes)
Console.Write(n.Name + (n == e ? "" : "->"));
}
[Category("Query")]
[Title("Equality of sequences")]
[Description("Check if 2 sequences of nodes are equal. " +
"Did Serge and peter co-author all of their the books?")]
public void XLinq38() {
XDocument doc = XDocument.Load(dataPath + "bib.xml");
var b1 = doc.Descendants("book")
.Where(b => b.Elements("author")
.Elements("first")
.Any(f => (string)f == "Serge"));
var b2 = doc.Descendants("book")
.Where(b => b.Elements("author")
.Elements("first")
.Any(f => (string)f == "Peter"));
bool result = b2.SequenceEqual(b1);
Console.WriteLine(result);
}
[Category("Query")]
[Title("TakeWhile operator")]
[Description("List books until total price is less that $150")]
public void XLinq39() {
XDocument doc = XDocument.Load(dataPath + "bib.xml");
double sum = 0;
var query = doc.Descendants("book")
.TakeWhile(c => (sum += (double)c.Element("price")) <= 150);
foreach (var result in query)
Console.WriteLine(result);
}
[Category("Query")]
[Title("Create a list of numbers")]
[Description("Create 5 new customers with different IDs")]
public void XLinq40() {
var query = from
i in Enumerable.Range(1, 5)
select
new XElement("Customer",
new XAttribute("id", i),
"New customer");
foreach (var result in query)
Console.WriteLine(result);
}
[Category("Query")]
[Title("Repeat operator")]
[Description("Initialize new orders with items")]
public void XLinq41() {
var orders = new XElement[] {
new XElement("order", new XAttribute("itemCount",5)),
new XElement("order", new XAttribute("itemCount",2)),
new XElement("order", new XAttribute("itemCount",3))};
//add empty items
foreach (var order in orders)
order.Add(Enumerable.Repeat(new XElement("item", "New item"),
(int)order.Attribute("itemCount")));
foreach (var o in orders)
Console.WriteLine(o);
}
[Category("Query")]
[Title("Any operator")]
[Description("Check if there are any customers in Argentina")]
public void XLinq42() {
XDocument doc = XDocument.Load(dataPath + "nw_Customers.xml");
if (doc.Descendants("Country").Any(c => (string)c == "Argentina"))
Console.WriteLine("There are cusotmers in Argentina");
else
Console.WriteLine("There are no cusotmers in Argentina");
}
[Category("Query")]
[Title("All operator")]
[Description("Check if all books have at least one author")]
public void XLinq43() {
XDocument doc = XDocument.Load(dataPath + "bib.xml");
bool query = doc.Descendants("book")
.All(b => b.Descendants("author").Count() > 0);
if (query)
Console.WriteLine("All books have authors");
else
Console.WriteLine("Some books dont have authors");
}
[Category("Query")]
[Title("Count operartor")]
[Description("Find the number of orders for a customer")]
public void XLinq44() {
XDocument doc = XDocument.Load(dataPath + "nw_Orders.xml");
var query = doc.Descendants("Orders")
.Where(o => (string)o.Element("CustomerID") == "VINET");
Console.WriteLine("Customer has {0} orders", query.Count());
}
[Category("Query")]
[Title("Aggregate operator")]
[Description("Find tax on an order")]
[LinkedMethod("Tax")]
public void XLinq45() {
string xml = "<order >" +
"<item price='150'>Motor</item>" +
"<item price='50'>Cable</item>" +
"</order>";
XElement order = XElement.Parse(xml);
double tax = order.Elements("item")
.Aggregate((double)0, Tax);
Console.WriteLine("The total tax on the order @10% is ${0}", tax);
}
static double Tax(double seed, XElement item) {
return seed + (double)item.Attribute("price") * 0.1;
}
[Category("Query")]
[Title("Distinct operator")]
[Description("Find all the countries where there is a customer")]
public void XLinq46() {
XDocument doc = XDocument.Load(dataPath + "nw_Customers.xml");
var countries = doc.Descendants("Country")
.Select(c => (string)c)
.Distinct()
.OrderBy(c => c);
foreach (var c in countries)
Console.WriteLine(c);
}
[Category("Query")]
[Title("Concat operator")]
[Description("List all books by Serge and Peter with co-authored books repeated")]
public void XLinq47() {
XDocument doc = XDocument.Load(dataPath + "bib.xml");
var b1 = doc.Descendants("book")
.Where(b => b.Elements("author")
.Elements("first")
.Any(f => (string)f == "Serge"));
var b2 = doc.Descendants("book")
.Where(b => b.Elements("author")
.Elements("first")
.Any(f => (string)f == "Peter"));
var books = b1.Concat(b2);
foreach (var b in books)
Console.WriteLine(b);
}
[Category("Query")]
[Title("Take operator")]
[Description("Query the first two customers")]
public void XLinq48() {
XDocument doc = XDocument.Load(dataPath + "nw_Customers.xml");
var customers = doc.Descendants("Customers").Take(2);
foreach (var c in customers)
Console.WriteLine(c);
}
[Category("Query")]
[Title("Skip operator")]
[Description("Skip the first 3 books")]
public void XLinq49() {
XDocument doc = XDocument.Load(dataPath + "bib.xml");
var books = doc.Descendants("book").Skip(3);
foreach (var b in books)
Console.WriteLine(b);
}
[Category("Query")]
[Title("Skip nodes based on a condition")]
[Description("Print items that dont fit in budget")]
public void XLinq50() {
string xml = "<order >" +
"<item price='150'>Motor</item>" +
"<item price='50'>Cable</item>" +
"<item price='50'>Modem</item>" +
"<item price='250'>Monitor</item>" +
"<item price='10'>Mouse</item>" +
"</order>";
XElement order = XElement.Parse(xml);
int sum = 0;
var items = order.Descendants("item")
.SkipWhile(i => (sum += (int)i.Attribute("price")) < 300);
foreach (var i in items)
Console.WriteLine("{0} does not fit in you budget", (string)i);
}
[Category("Query")]
[Title("SelectMany operator")]
[Description("Get all books authored by Serge and Peter")]
[LinkedMethod("GetBooks")]
public void XLinq51() {
string[] authors = { "Serge", "Peter" };
var books = authors.SelectMany(a => GetBooks(a));
foreach (var b in books)
Console.WriteLine(b);
}
public IEnumerable<XElement> GetBooks(string author) {
XDocument doc = XDocument.Load(dataPath + "bib.xml");
var query = doc.Descendants("book")
.Where(b => b.Elements("author")
.Elements("first")
.Any(f => (string)f == author));