1: 6.1 test.xml
2: <?xml version="1.0" encoding="utf-8"?>
3: <TabAddressBookEntity xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/DemoOrder">
4: <Address i:nil="true" />
5: <Age>19</Age>
6: <Company i:nil="true" />
7: <Duty>乖巧人儿</Duty>
8: <MainID>4</MainID>
9: <Name>董巧巧</Name>
10: <Sex>女</Sex>
11: <TabShoppingListEntity>
12: <TabShoppingListEntity>
13: <AddressBookID>4</AddressBookID>
14: <Amount>1</Amount>
15: <Date i:nil="true" />
16: <ID>9</ID>
17: <Price>60000.0000</Price>
18: <Product>1克拉钻石戒指</Product>
19: <Unit>个</Unit>
20: </TabShoppingListEntity>
21: <TabShoppingListEntity>
22: <AddressBookID>4</AddressBookID>
23: <Amount>1</Amount>
24: <Date i:nil="true" />
25: <ID>10</ID>
26: <Price>1000000.0000</Price>
27: <Product>旺角酒楼</Product>
28: <Unit>座</Unit>
29: </TabShoppingListEntity>
30: </TabShoppingListEntity>
31: <TelphoneNumber>029*-981256**</TelphoneNumber>
32: </TabAddressBookEntity>
33:
34:
35: using System;
36: using System.Collections.Generic;
37: using System.IO;
38: using System.Linq;
39: using System.Xml.Linq;
40: ////// <summary>
41: /// 查询 test.xml
42: /// </summary>
43: namespace DemoLinqToXml
44: {
45: class Program
46: {
47: static void Main(string[] args)
48: {
49: XDocument xdoc = null;
50:
51: using (StreamReader sr = new StreamReader("test.xml"))
52: {
53: //从文件中载入XML
54: xdoc = XDocument.Parse(sr.ReadToEnd());
55: }
56:
57: //使用LINQ表达式查找Product节点,获取节点的值
58: IEnumerable<string> products = from ele in xdoc.Descendants()
59: where ele.Name.LocalName == "Product"
60: select ele.Value;
61:
62:
63: foreach (string p in products)
64: Console.WriteLine(p);
65:
66: Console.ReadKey();
67: }
68: }
69: }
70:
71:
72: /// <summary>
73: /// 从Internet 装载XML文档构建XDocument
74: /// </summary>
75:
76: using System;
77: using System.Xml.Linq;
78:
79: namespace DemoXDocument
80: {
81: class Program
82: {
83: static void Main(string[] args)
84: {
85: //从URI加载 XML 文档生成 XDocument 对象
86: XDocument doc = XDocument.Load("http://rss.sina.com.cn/news/marquee/ddt.xml");
87:
88: //为了方便查看,省略一些子节点
89: doc.Descendants("item").Remove();
90:
91: //为了方便查看,省略注释的一些内容
92: foreach (var n in doc.Nodes())
93: {
94: XComment comm = n as XComment;
95: if (comm != null)
96: comm.Value = string.Format("{0} ...... ",comm.Value.Substring(0, 30));
97: }
98:
99: Console.WriteLine(doc);
100: Console.ReadKey();
101: }
102: }
103: }
104:
105: ////// <summary>
106: ///
107: /// 给XDocument 对象增加元素
108: ///
109: /// </summary>
110:
111: using System;
112: using System.Xml.Linq;
113:
114: namespace DemoXAttribute1
115: {
116: class Program
117: {
118: static void Main(string[] args)
119: {
120: XElement root = new XElement("根元素",
121: new XAttribute("属性1", "值"),
122: new XAttribute("属性2", "0"));
123:
124: XElement child = new XElement("子元素1");
125: child.Add(new XAttribute("子节点上的属性", "**"));
126:
127: XDocument doc = new XDocument(root);
128:
129: doc.Root.Add(child,
130: new XElement("子元素2", "元素值"),
131: new XElement("子元素3")
132: );
133:
134:
135: Console.WriteLine(doc);
136: Console.ReadKey();
137: }
138: }
139: }
140:
141: ////// <summary>
142: /// XComment("这是根节点的注释内容")
143: /// </summary>
144: using System;
145: using System.Xml.Linq;
146:
147: namespace DemoXComment
148: {
149: class Program
150: {
151: static void Main(string[] args)
152: {
153: XElement root = new XElement("根元素",
154: new XComment("这是根节点的注释内容"),
155: new XAttribute("属性", "0"));
156:
157: XDocument doc = new XDocument(new XComment("这是文档的注释内容"),root);
158:
159: doc.Root.Add(new XElement("子元素", "元素值"),
160: new XElement("子元素")
161: );
162:
163:
164: Console.WriteLine(doc);
165: Console.ReadKey();
166: }
167: }
168: }
169:
170: ////// <summary>
171: /// 使用XDeclaration 给XDocument对象增加声明
172: /// </summary>
173:
174: using System;
175: using System.IO;
176: using System.Xml;
177: using System.Xml.Linq;
178: using System.Text;
179:
180: namespace DemoXDeclaration
181: {
182: class Program
183: {
184: static void Main(string[] args)
185: {
186: XElement root = new XElement("根元素",
187: new XAttribute("属性", "0"));
188:
189: XDocument doc = new XDocument(new XComment("这是文档的注释内容"), root);
190:
191: doc.Declaration = new XDeclaration("1.0", "utf-16", "yes");
192:
193: doc.Root.Add(new XElement("子元素"),
194: new XElement("子元素")
195: );
196:
197: StringWriter sw = new StringWriter();
198: doc.Save(sw, SaveOptions.None);
199: sw.Close();
200:
201: Console.WriteLine(sw.ToString());
202:
203: Console.ReadKey();
204: }
205: }
206: }
207:
208: ////// <summary>
209: /// XDocumentType 表示文档类型
210: /// </summary>
211:
212: using System;
213: using System.Xml.Linq;
214:
215: namespace DemoXDocumentType
216: {
217: class Program
218: {
219: static void Main(string[] args)
220: {
221: XElement root = new XElement("根元素",
222: new XAttribute("属性", "0"));
223:
224: XDocument doc = new XDocument(
225: new XDocumentType("限定名","Test Name","专用标识符","内部子集"),
226: new XComment("这是文档的注释内容"), root);
227:
228:
229: doc.Root.Add(new XElement("子元素"),
230: new XElement("子元素")
231: );
232:
233: Console.WriteLine(doc);
234:
235: Console.ReadKey();
236: }
237: }
238: }
239:
240:
241: ////// <summary>
242: /// XProcessingInstruction 表示XML出来命令
243: /// </summary>
244:
245: using System;
246: using System.Xml.Linq;
247:
248: namespace DemoXProcessingInstruction
249: {
250: class Program
251: {
252: static void Main(string[] args)
253: {
254: XElement root = new XElement("根元素",
255: new XAttribute("属性", "0"));
256:
257: XDocument doc = new XDocument(
258: new XProcessingInstruction ("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
259: new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
260: new XComment("这是文档的注释内容"), root);
261:
262:
263: doc.Root.Add(new XElement("子元素"),
264: new XElement("子元素")
265: );
266:
267: Console.WriteLine(doc);
268:
269: Console.ReadKey();
270: }
271: }
272: }
273:
274: ////// <summary>
275: /// XCData 表示一个文本节点
276: /// </summary>
277:
278: using System;
279: using System.Xml.Linq;
280:
281: namespace DemoXCdata
282: {
283: class Program
284: {
285: static void Main(string[] args)
286: {
287: XElement root = new XElement("根元素",
288: new XAttribute("属性", "0")
289: );
290:
291: XDocument doc = new XDocument(
292: new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
293: new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
294: new XComment("这是文档的注释内容"), root);
295:
296:
297: root.Add(new XElement("子元素"),
298:
299: new XElement("子元素")
300: );
301:
302: root.Add(new XCData("这里是根元素的CDATA节点"));
303:
304: Console.WriteLine(doc);
305:
306: Console.ReadKey();
307: }
308: }
309: }
310:
311: ////// <summary>
312: /// XNamespace sp = "http://www.tiyor.com";命名空间
313: /// </summary>
314: using System;
315: using System.Xml.Linq;
316:
317: namespace DemoXNamespace
318: {
319: class Program
320: {
321: static void Main(string[] args)
322: {
323: XNamespace sp = "http://www.tiyor.com";
324:
325: XElement root = new XElement(sp + "根元素",
326: new XAttribute("属性", "0")
327: );
328:
329: XDocument doc = new XDocument(
330: new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
331: new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
332: new XComment("这是文档的注释内容"), root);
333:
334:
335: root.Add(new XElement(sp + "子元素"),
336: new XElement(sp + "子元素")
337: );
338:
339: root.Add(new XCData("这里是根元素的CDATA节点"));
340:
341: Console.WriteLine(doc);
342:
343: Console.ReadKey();
344:
345: }
346: }
347: }
348: ////// <summary>
349: /// 构建XEelement
350: ///
351: /// </summary>
352: using System;
353: using System.Collections.Generic;
354: using System.Linq;
355: using System.Text;
356: using System.Xml.Linq;
357:
358: namespace DemoXElement
359: {
360: class Program
361: {
362: static void Main(string[] args)
363: {
364: //使用原型一构建
365: XElement el1 = new XElement("原型1根节点");
366: Console.WriteLine(el1);
367:
368: Console.WriteLine("***********************************");
369:
370: //使用原型2构建
371: XElement el2 = new XElement(el1);
372: el2.Name = "原型2根节点";
373: Console.WriteLine(el2);
374:
375: Console.WriteLine("***********************************");
376:
377: //使用原型3构建
378: XElement el3 = new XElement(
379: new XStreamingElement("原型3根节点",
380: from el in el1.Elements()
381: select el
382: )
383: );
384: Console.WriteLine(el3);
385:
386: Console.WriteLine("***********************************");
387:
388: //使用原型4构建
389: XElement el4 = new XElement("原型4根节点",new XElement("原型4的子节点"));
390: Console.WriteLine(el4);
391:
392: Console.WriteLine("***********************************");
393:
394:
395: //使用原型5构建
396: XElement el5 = new XElement("原型5根节点",
397: new XElement("原型5的子节点",1),
398: new XElement("原型5的子节点",2),
399: new XElement("原型5的子节点",3)
400: );
401: Console.WriteLine(el5);
402:
403: Console.ReadKey();
404:
405: }
406: }
407: }
408:
409:
410:
411: ////// <summary>
412: /// Parse 方法 与使用Element 检索元素的轴方法
413: /// </summary>
414:
415: using System;
416: using System.Xml.Linq;
417:
418: namespace DemoXElementMethod
419: {
420: class Program
421: {
422: static void Main(string[] args)
423: {
424: string sxml = @"<根节点>
425: <子节点>1</子节点>
426: <子节点>2</子节点>
427: <子节点>3</子节点>
428: <子节点>4</子节点>
429: <子节点>5</子节点>
430: <子节点>6</子节点>
431: </根节点>";
432:
433:
434: XElement el = XElement.Parse(sxml);
435:
436: XElement elChild = el.Element("子节点");
437:
438: Console.WriteLine(elChild);
439:
440: Console.ReadKey();
441: }
442: }
443: }
444:
445:
446: ////// <summary>
447: /// Elements\Descendants 方法检索子元素集合
448: /// </summary>
449: using System;
450: using System.Collections.Generic;
451: using System.Xml.Linq;
452:
453: namespace DemoXElements
454: {
455: class Program
456: {
457: static void Main(string[] args)
458: {
459: string sxml = @"<根节点>
460: <子节点>
461: <第3级>1</第3级>
462: <第3级>2</第3级>
463: </子节点>
464: <子节点>2</子节点>
465: <子节点>3</子节点>
466: <子节点>4</子节点>
467: <子节点>5</子节点>
468: <子节点>6</子节点>
469: </根节点>";
470:
471: XElement el = XElement.Parse(sxml);
472:
473: Console.WriteLine("应用Elements方法返回的子元素集合");
474: IEnumerable<XElement> elChilds = el.Elements();
475: foreach (XElement e in elChilds)
476: Console.WriteLine(e.Name.LocalName);
477:
478: Console.WriteLine("\n应用Descendants方法返回的子元素集合");
479: IEnumerable<XElement> elChilds2 = el.Descendants();
480: foreach (XElement e in elChilds2)
481: Console.WriteLine(e.Name.LocalName);
482:
483: Console.ReadKey();
484: }
485: }
486: }
487:
488: ////// <summary>
489: /// Ancestors\ AncestorsAndSelf 方法检索父级元素
490: /// </summary>
491:
492: using System;
493: using System.Linq;
494: using System.Xml.Linq;
495:
496: namespace DemoXAncestors
497: {
498: class Program
499: {
500: static void Main(string[] args)
501: {
502:
503: string sxml = @"<根节点>
504: <子节点1>
505: <第3级节点 />
506: </子节点1>
507: <子节点2 />
508: <子节点3 />
509: <子节点4 />
510: </根节点>";
511:
512: XElement el = XElement.Parse(sxml);
513:
514: XElement el2 = el.Descendants("第3级节点").First();
515:
516: Console.WriteLine("应用Ancestors方法返回父元素集合");
517: foreach(XElement e in el2.Ancestors())
518: Console.WriteLine(e.Name.LocalName);
519:
520: Console.WriteLine("\n应用AncestorsAndSelf方法返回父元素集合");
521: foreach (XElement e in el2.AncestorsAndSelf())
522: Console.WriteLine(e.Name.LocalName);
523:
524:
525: Console.ReadKey();
526: }
527: }
528: }
529:
530: ////// <summary>
531: /// 应用ElementsAfterSelf方法返回该元素之后同级的元素集合
532: /// 应用ElementsBeforeSelf方法返回该元素之前同级的元素集合
533: /// </summary>
534:
535: using System;
536: using System.Collections.Generic;
537: using System.Xml.Linq;
538:
539: namespace DemoXElementsMethod
540: {
541: class Program
542: {
543: static void Main(string[] args)
544: {
545: string sxml = @"<根节点>
546: <子节点1 />
547: <子节点2 />
548: <Test子节点 />
549: <子节点4 />
550: <子节点5 />
551: <子节点6 />
552: </根节点>";
553:
554:
555: XElement el = XElement.Parse(sxml);
556:
557: IEnumerable<XElement> els = el.Element("Test子节点").ElementsAfterSelf();
558: Console.WriteLine("应用ElementsAfterSelf方法返回的元素集合");
559: foreach (XElement e in els)
560: Console.WriteLine(e);
561:
562: IEnumerable<XElement> els2 = el.Element("Test子节点").ElementsBeforeSelf();
563: Console.WriteLine("应用ElementsBeforeSelf方法返回的元素集合");
564: foreach (XElement e in els2)
565: Console.WriteLine(e);
566:
567: Console.ReadKey();
568: }
569: }
570: }
571:
572: ////// <summary>
573: /// XValue
574: /// </summary>
575:
576: using System;
577: using System.Xml.Linq;
578:
579: namespace DemoXValue
580: {
581: class Program
582: {
583: static void Main(string[] args)
584: {
585: string sxml = @"<根节点>
586: <子节点>1</子节点>
587: <子节点>
588: <第3级>1</第3级>
589: <第3级>2</第3级>
590: </子节点>
591: <子节点2>2</子节点2>
592: <子节点3>字符串值</子节点3>
593: <子节点>4</子节点>
594: </根节点>";
595:
596: XElement el = XElement.Parse(sxml);
597:
598: Console.WriteLine("第一个子节点的值:{0}", el.Element("子节点").Value);
599:
600: string svalue = (string)el.Element("子节点3");
601: Console.WriteLine("强制转换得到子节点3的值:{0}", svalue);
602:
603: int? ivalue = (int?)el.Element("不存在的节点");
604: Console.WriteLine("可空类型的强制转换:{0}", ivalue == null ? "值为null" : ivalue.ToString());
605:
606: int ivalue2 = (int)el.Element("子节点2");
607: Console.WriteLine("强制转换得到子节点2的值:{0}", ivalue2);
608:
609: el.Element("子节点2").Value = "字符串值";
610: Console.WriteLine("子节点2的Value:{0}", el.Element("子节点2").Value);
611:
612: el.Element("子节点2").SetValue(12345);
613: Console.WriteLine("子节点2的Value:{0}", el.Element("子节点2").Value);
614:
615: Console.ReadKey();
616: }
617: }
618: }
619:
620:
621: ////// <summary>
622: /// Add\AddAfterSelf\AddBeforeSelf\AddFirst
623: /// </summary>
624:
625:
626: using System;
627: using System.Xml.Linq;
628:
629: namespace DemoXAdd
630: {
631: class Program
632: {
633: static void Main(string[] args)
634: {
635: XElement el = new XElement("根节点");
636:
637: el.Add(new XElement("Add添加的子节点"));
638:
639: el.Add(new XElement("Add添加的子节点"),
640: new XElement("Add添加的子节点")
641: );
642:
643: el.AddFirst(new XElement("AddFirst添加的子节点"));
644:
645: el.Element("AddFirst添加的子节点").AddAfterSelf(new XElement("AddAfterSelf添加的节点"));
646:
647: el.Element("AddFirst添加的子节点").AddBeforeSelf(new XElement("AddBeforeSelf添加的节点"));
648:
649: Console.WriteLine(el);
650:
651: Console.ReadKey();
652: }
653: }
654: }
655:
656: 运行结果:
657: <根节点>
658: <AddBeforeSelf添加的节点 />
659: <AddFirst添加的子节点 />
660: <AddAfterSelf添加的节点 />
661: <Add添加的子节点 />
662: <Add添加的子节点 />
663: <Add添加的子节点 />
664: </根节点>
665:
666: ////// <summary>
667: /// Remove\RemoveAll 删除元素
668: /// </summary>
669:
670: using System;
671: using System.Xml.Linq;
672:
673: namespace DemoXRemove
674: {
675: class Program
676: {
677: static void Main(string[] args)
678: {
679: XElement el = new XElement("根节点");
680:
681: el.Add(new XElement("子节点1"),
682: new XElement("子节点2"),
683: new XElement("子节点3"),
684: new XElement("子节点4")
685: );
686:
687: el.Element("子节点3").Remove();
688:
689: Console.WriteLine(el);
690:
691: el.RemoveAll();
692:
693: Console.WriteLine("\n对根节点应用RemoveAll方法后");
694: Console.WriteLine(el);
695: Console.ReadKey();
696: }
697: }
698: }
699:
700:
701: ////// <summary>
702: /// ReplaceWith 替换元素
703: /// </summary>
704:
705: using System;
706: using System.Xml.Linq;
707:
708: namespace DemoXReplaceWith
709: {
710: class Program
711: {
712: static void Main(string[] args)
713: {
714: string sxml = @"<根节点>
715: <子节点1 />
716: <子节点2 />
717: <子节点3 />
718: <子节点4 />
719: </根节点>";
720:
721: XElement el = XElement.Parse(sxml);
722:
723: el.Element("子节点2").ReplaceWith(new XElement("原型一替换的"));
724: Console.WriteLine("应用ReplaceWith原型一之后");
725: Console.WriteLine(el);
726:
727: el.Element("子节点3").ReplaceWith(new XElement("替换3"), new XElement("新加入"));
728: Console.WriteLine("\n应用ReplaceWith原型二之后");
729: Console.WriteLine(el);
730:
731: Console.ReadKey();
732: }
733: }
734: }
735:
736: ////// <summary>
737: /// ReplaceAll方法替换元素的子节点
738: /// </summary>
739:
740: using System;
741: using System.Xml.Linq;
742:
743: namespace DemoXReplaceAll
744: {
745: class Program
746: {
747: static void Main(string[] args)
748: {
749: string sxml = @"<根节点>
750: <子节点1 />
751: <子节点2 />
752: <子节点3 />
753: <子节点4 />
754: </根节点>";
755:
756: XElement el = XElement.Parse(sxml);
757:
758: el.Element("子节点2").ReplaceAll(new XElement("ReplaceAll原型一"));
759: Console.WriteLine("应用ReplaceAll原型一之后");
760: Console.WriteLine(el);
761:
762: el.Element("子节点3").ReplaceAll(new XElement("ReplaceAll原型二"), new XElement("ReplaceAll原型二"));
763: Console.WriteLine("\n应用ReplaceAll原型二之后");
764: Console.WriteLine(el);
765:
766: Console.ReadKey();
767: }
768: }
769: }
770:
771:
772: ////// <summary>
773: /// SetElementValue
774: /// </summary>
775: using System;
776: using System.Xml.Linq;
777:
778: namespace DemoXSetElementValue
779: {
780: class Program
781: {
782: static void Main(string[] args)
783: {
784: string sxml = @"<根节点>
785: <子节点1>
786: <第3级 />
787: </子节点1>
788: <子节点2 />
789: <子节点3 />
790: <子节点4 />
791: </根节点>";
792:
793: XElement el = XElement.Parse(sxml);
794:
795: //移除第3级子元素
796: el.Element("子节点1").SetElementValue("第3级", null);
797:
798: //新添加子元素
799: el.Element("子节点1").SetElementValue("新添加子元素", "测试值");
800:
801: Console.WriteLine(el.Element("子节点1"));
802:
803: //修改新添加子元素
804: el.Element("子节点1").SetElementValue("新添加子元素", "修改值");
805:
806: Console.WriteLine(el.Element("子节点1"));
807:
808: Console.ReadKey();
809: }
810: }
811: }
812:
813:
814: ////// <summary>
815: /// Attributes 获取元素的属性集合
816: /// </summary>
817:
818: using System;
819: using System.Xml.Linq;
820:
821: namespace DemoXAttributes
822: {
823: class Program
824: {
825: static void Main(string[] args)
826: {
827: string sxml = @"<根节点>
828: <子节点1 属性1='1' 属性2='测试' />
829: <子节点2 />
830: <子节点3 />
831: <子节点4 />
832: </根节点>";
833:
834: XElement el = XElement.Parse(sxml);
835:
836: foreach( var a in el.Element("子节点1").Attributes())
837: Console.WriteLine(a);
838:
839: Console.ReadKey();
840:
841: }
842: }
843: }
844:
845: using System;
846: using System.Xml.Linq;
847:
848: namespace DemoXAttribute
849: {
850: class Program
851: {
852: static void Main(string[] args)
853: {
854: string sxml = @"<根节点>
855: <子节点1 属性1='1' 属性2='测试' />
856: <子节点2 />
857: <子节点3 />
858: <子节点4 />
859: </根节点>";
860:
861: XElement el = XElement.Parse(sxml);
862:
863: Console.WriteLine(el.Element("子节点1").Attribute("属性2"));
864:
865: Console.WriteLine(el.Element("子节点1").Attribute("属性3") == null ? "属性3并不存在" : el.Element("子节点1").Attribute("属性3").ToString());
866:
867: Console.ReadKey();
868: }
869: }
870: }
871:
872:
873: ////// <summary>
874: /// ReplaceAttributes 方法替换属性
875: /// </summary>
876:
877: using System;
878: using System.Xml.Linq;
879:
880: namespace DemoXReplaceAttributes
881: {
882: class Program
883: {
884: static void Main(string[] args)
885: {
886: string sxml = @"<根节点>
887: <子节点1 属性1='测试'/>
888: <子节点2 />
889: <子节点3 />
890: <子节点4 />
891: </根节点>";
892:
893: XElement el = XElement.Parse(sxml);
894:
895: el.Element("子节点1").ReplaceAttributes(new XAttribute("原型一替换",0));
896: Console.WriteLine("应用ReplaceAttributes原型一之后");
897: Console.WriteLine(el.Element("子节点1"));
898:
899: el.Element("子节点1").ReplaceAttributes(new XAttribute("原型二替换",0), new XAttribute("原型二添加",0));
900: Console.WriteLine("\n应用ReplaceAttributes原型二之后");
901: Console.WriteLine(el.Element("子节点1"));
902:
903: Console.ReadKey();
904: }
905: }
906: }
907:
908: using System;
909: using System.Xml.Linq;
910:
911: namespace DemoXRemoveAttributes
912: {
913: class Program
914: {
915: static void Main(string[] args)
916: {
917: string sxml = @"<根节点>
918: <子节点1 属性1='测试' 属性2='0'>
919: <第3级 属性='1'/>
920: </子节点1>
921: <子节点2 />
922: </根节点>";
923:
924: XElement el = XElement.Parse(sxml);
925:
926: Console.WriteLine("应用RemoveAttributes之后");
927:
928: el.Element("子节点1").RemoveAttributes();
929:
930: Console.WriteLine(el);
931:
932: el.Element("子节点1").RemoveAll();
933:
934: Console.WriteLine("\n应用RemoveAll之后");
935: Console.WriteLine(el);
936: Console.ReadKey();
937: }
938: }
939: }
940:
941: using System;
942: using System.Xml.Linq;
943:
944: namespace DemoXSetAttributeValue
945: {
946: class Program
947: {
948: static void Main(string[] args)
949: {
950: string sxml = @"<根节点>
951: <子节点1 属性1='测试'/>
952: <子节点2 />
953: <子节点3 />
954: <子节点4 />
955: </根节点>";
956:
957: XElement el = XElement.Parse(sxml);
958:
959: //移除属性1
960: el.Element("子节点1").SetAttributeValue("属性1", null);
961:
962: //添加属性Test
963: el.Element("子节点1").SetAttributeValue("属性Test", "测试值");
964:
965: Console.WriteLine(el.Element("子节点1"));
966:
967: //修改属性Test
968: el.Element("子节点1").SetAttributeValue("属性Test", "修改值");
969:
970: Console.WriteLine(el.Element("子节点1"));
971:
972: Console.ReadKey();
973: }
974: }
975: }
976: using System;
977: using System.Xml.Linq;
978:
979: namespace DemoXAnnotations
980: {
981: class Program
982: {
983: static void Main(string[] args)
984: {
985: string sxml = @"<根节点>
986: <子节点1 />
987: <子节点2 />
988: <子节点3 />
989: <子节点4 />
990: </根节点>";
991:
992:
993: XElement el = XElement.Parse(sxml);
994: el.Element("子节点1").AddAnnotation("批注1");
995: el.Element("子节点1").AddAnnotation("批注2");
996: el.Element("子节点1").AddAnnotation("批注3");
997: Console.WriteLine("子节点1的批注对象");
998:
999: //访问批注对象集合
1000: foreach (string s in el.Element("子节点1").Annotations<string>())
1001: Console.WriteLine(s);
1002:
1003: Console.ReadKey();
1004: }
1005: }
1006: }
1007:
1008: using System;
1009: using System.Linq;
1010: using System.Text;
1011: using System.Xml.Linq;
1012:
1013: namespace DemoXRemoveAnnotations
1014: {
1015: class Program
1016: {
1017: static void Main(string[] args)
1018: {
1019: string sxml = @"<根节点>
1020: <子节点1>
1021: <第3级 />
1022: </子节点1>
1023: <子节点2 />
1024: <子节点3 />
1025: <子节点4 />
1026: </根节点>";
1027:
1028:
1029: XElement el = XElement.Parse(sxml);
1030: el.Element("子节点1").AddAnnotation("批注1");
1031: el.Element("子节点1").AddAnnotation("批注2");
1032: el.Element("子节点1").AddAnnotation("批注3");
1033: el.Element("子节点1").AddAnnotation(new StringBuilder());
1034: el.Element("子节点1").AddAnnotation(new StringBuilder());
1035:
1036:
1037: el.Element("子节点1").Element("第3级").AddAnnotation("第3级批注");
1038:
1039: el.Element("子节点1").RemoveAnnotations<string>();
1040: Console.WriteLine("子节点1的string批注对象数:{0}", el.Element("子节点1").Annotations<string>().Count());
1041: Console.WriteLine("子节点1的StringBuilder批注对象数:{0}", el.Element("子节点1").Annotations<StringBuilder>().Count());
1042:
1043: Console.WriteLine("第3级的string批注对象数:{0}", el.Element("子节点1").Element("第3级").Annotations<string>().Count());
1044:
1045: Console.ReadKey();
1046: }
1047: }
1048:
1049: }
1050:
1051: ///summary
1052: ///查询
1053: ///summary
1054:
1055: using System;
1056: using System.Linq;
1057: using System.Xml.Linq;
1058:
1059: namespace DemoXQuery1
1060: {
1061: class Program
1062: {
1063: static void Main(string[] args)
1064: {
1065: string sxml = @"<通讯录>
1066: <客户 姓名='肖青漩' 年龄='21'>
1067: <职务>出云公主</职务>
1068: <电话>017*-876543**</电话>
1069: </客户>
1070: <客户 姓名='董巧巧' 年龄='19'>
1071: <职务>乖巧人儿</职务>
1072: <电话>029*-981256**</电话>
1073: </客户>
1074: <客户 姓名='萧玉霜' 年龄='17'>
1075: <职务>萧家二小姐</职务>
1076: <电话>053*-985690**</电话>
1077: </客户>
1078: </通讯录>";
1079:
1080: XElement root = XElement.Parse(sxml);
1081:
1082: //筛选年龄属性大于18的客户
1083: var query = from item in root.Elements("客户")
1084: where (from att in item.Attributes()
1085: where att.Name.LocalName == "年龄"
1086: select att).Any(age=>(int)age>18)
1087: select item;
1088:
1089: foreach (var el in query)
1090: Console.WriteLine(el);
1091:
1092: Console.ReadKey();
1093:
1094: }
1095: }
1096: }
1097:
1098:
1099: ////// <summary>
1100: /// Order 对XML元素进行排序
1101: /// </summary>
1102:
1103: using System;
1104: using System.Linq;
1105: using System.Xml.Linq;
1106:
1107: namespace DemoXOrder
1108: {
1109: class Program
1110: {
1111: static void Main(string[] args)
1112: {
1113: string sxml = @"<通讯录>
1114: <客户 姓名='肖青漩' 年龄='21'>
1115: <职务>出云公主</职务>
1116: <电话>017*-876543**</电话>
1117: </客户>
1118: <客户 姓名='董巧巧' 年龄='19'>
1119: <职务>乖巧人儿</职务>
1120: <电话>029*-981256**</电话>
1121: </客户>
1122: <客户 姓名='萧玉霜' 年龄='17'>
1123: <职务>萧家二小姐</职务>
1124: <电话>053*-985690**</电话>
1125: </客户>
1126: <客户 姓名='秦仙儿' 年龄='20'>
1127: <职务>霓裳公主</职务>
1128: <电话>023*-338987**</电话>
1129: </客户>
1130: <客户 姓名='萧玉若' 年龄='21'>
1131: <职务>萧家大小姐</职务>
1132: <电话>035*-120967**</电话>
1133: </客户>
1134: <客户 姓名='洛凝' 年龄='19'>
1135: <职务>金陵才女</职务>
1136: <电话>033*-985690**</电话>
1137: </客户>
1138: </通讯录>";
1139:
1140: XElement root = XElement.Parse(sxml);
1141:
1142: var query = from item in root.Elements("客户")
1143: orderby (int)item.Attribute("年龄"), item.Element("电话").Value
1144: select item;
1145:
1146: foreach (var el in query)
1147: Console.WriteLine(el);
1148:
1149: Console.ReadKey();
1150: }
1151: }
1152: }
1153:
1154:
1155:
1156: ////// <summary>
1157: /// 对XMLelment 元素进行计算
1158: /// </summary>
1159:
1160: using System;
1161: using System.Linq;
1162: using System.Xml.Linq;
1163:
1164: namespace DemoXCount
1165: {
1166: class Program
1167: {
1168: static void Main(string[] args)
1169: {
1170: string sxml = @"<通讯录>
1171: <客户 姓名='肖青漩' 年龄='21'>
1172: <职务>出云公主</职务>
1173: <电话>017*-876543**</电话>
1174: <订货单>
1175: <品名>6克拉钻石戒指</品名>
1176: <单价>120,000</单价>
1177: <数量>3</数量>
1178: </订货单>
1179: <订货单>
1180: <品名>真丝旗袍</品名>
1181: <单价>3,600</单价>
1182: <数量>2</数量>
1183: </订货单>
1184: </客户>
1185: <客户 姓名='董巧巧' 年龄='19'>
1186: <职务>乖巧人儿</职务>
1187: <电话>029*-981256**</电话>
1188: <订货单>
1189: <品名>旺角酒楼</品名>
1190: <单价>2,500,000</单价>
1191: <数量>1</数量>
1192: </订货单>
1193: <订货单>
1194: <品名>奥迪TT</品名>
1195: <单价>650,000</单价>
1196: <数量>1</数量>
1197: </订货单>
1198: </客户>
1199: <客户 姓名='萧玉霜' 年龄='17'>
1200: <职务>萧家二小姐</职务>
1201: <电话>053*-985690**</电话>
1202: </客户>
1203: <客户 姓名='秦仙儿' 年龄='20'>
1204: <职务>霓裳公主</职务>
1205: <电话>023*-338987**</电话>
1206: <订货单>
1207: <品名>独门四合院</品名>
1208: <单价>12,000,000</单价>
1209: <数量>1</数量>
1210: </订货单>
1211: </客户>
1212: <客户 姓名='萧玉若' 年龄='21'>
1213: <职务>萧家大小姐</职务>
1214: <电话>035*-120967**</电话>
1215: </客户>
1216: <客户 姓名='洛凝' 年龄='19'>
1217: <职务>金陵才女</职务>
1218: <电话>033*-985690**</电话>
1219: </客户>
1220: </通讯录>";
1221:
1222: XElement root = XElement.Parse(sxml);
1223:
1224: var query = from item in root.Elements("客户")
1225: let cc = (from l in item.Elements("订货单")
1226: let c = Convert.ToDouble(l.Element("单价").Value) * (double)l.Element("数量")
1227: select c).Sum()
1228: orderby cc descending
1229: select new { Guest = item, Count = cc };
1230:
1231: foreach (var item in query)
1232: {
1233: Console.WriteLine("姓名:{0} 订单总价:{1}", item.Guest.Attribute("姓名").Value, item.Count.ToString("C"));
1234: foreach (var p in item.Guest.Elements("订货单"))
1235: Console.WriteLine("{0} {1} {2}", p.Element("品名").Value, p.Element("单价").Value, p.Element("数量").Value);
1236: Console.WriteLine("----------------------------------------------");
1237: }
1238:
1239: Console.ReadKey();
1240: }
1241: }
1242: }
1243:
1244:
1245: ////// <summary>
1246: /// 剔除XML中符合条件的元素
1247: /// </summary>
1248:
1249: using System;
1250: using System.Linq;
1251: using System.Xml.Linq;
1252:
1253: namespace DemoLinqRemove
1254: {
1255: class Program
1256: {
1257: static void Main(string[] args)
1258: {
1259: string sxml = @"<通讯录>
1260: <客户 姓名='肖青漩' 年龄='21'>
1261: <职务>出云公主</职务>
1262: <电话>017*-876543**</电话>
1263: <订货单>
1264: <品名>6克拉钻石戒指</品名>
1265: <单价>120,000</单价>
1266: <数量>3</数量>
1267: </订货单>
1268: <订货单>
1269: <品名>真丝旗袍</品名>
1270: <单价>3,600</单价>
1271: <数量>2</数量>
1272: </订货单>
1273: </客户>
1274: <客户 姓名='董巧巧' 年龄='19'>
1275: <职务>乖巧人儿</职务>
1276: <电话>029*-981256**</电话>
1277: <订货单>
1278: <品名>旺角酒楼</品名>
1279: <单价>2,500,000</单价>
1280: <数量>1</数量>
1281: </订货单>
1282: <订货单>
1283: <品名>奥迪TT</品名>
1284: <单价>650,000</单价>
1285: <数量>1</数量>
1286: </订货单>
1287: </客户>
1288: <客户 姓名='萧玉霜' 年龄='17'>
1289: <职务>萧家二小姐</职务>
1290: <电话>053*-985690**</电话>
1291: </客户>
1292: <客户 姓名='秦仙儿' 年龄='20'>
1293: <职务>霓裳公主</职务>
1294: <电话>023*-338987**</电话>
1295: <订货单>
1296: <品名>独门四合院</品名>
1297: <单价>12,000,000</单价>
1298: <数量>1</数量>
1299: </订货单>
1300: </客户>
1301: <客户 姓名='萧玉若' 年龄='21'>
1302: <职务>萧家大小姐</职务>
1303: <电话>035*-120967**</电话>
1304: </客户>
1305: <客户 姓名='洛凝' 年龄='19'>
1306: <职务>金陵才女</职务>
1307: <电话>033*-985690**</电话>
1308: </客户>
1309: </通讯录>";
1310:
1311: XElement root = XElement.Parse(sxml);
1312:
1313: //剔除订单总价等于0的客户
1314: (from item in root.Elements("客户")
1315: let cc = (from l in item.Elements("订货单")
1316: let c = Convert.ToDouble(l.Element("单价").Value) * (double)l.Element("数量")
1317: select c).Sum()
1318: where cc == 0
1319: select item).Remove();
1320:
1321: //剔除XML树中的订单
1322: (from item in root.Elements("客户")
1323: from l in item.Elements("订货单")
1324: select l).Remove();
1325:
1326: Console.WriteLine(root);
1327:
1328: Console.ReadKey();
1329: }
1330: }
1331: }
1332: ////// <summary>
1333: /// 变造XML树
1334: /// </summary>
1335: using System;
1336: using System.Linq;
1337: using System.Xml.Linq;
1338:
1339: namespace DemoTransforming
1340: {
1341: class Program
1342: {
1343: static void Main(string[] args)
1344: {
1345: string sxml = @"<通讯录>
1346: <客户 姓名='肖青漩' 年龄='21'>
1347: <职务>出云公主</职务>
1348: <电话>017*-876543**</电话>
1349: <订货单>
1350: <品名>6克拉钻石戒指</品名>
1351: <单价>120,000</单价>
1352: <数量>3</数量>
1353: </订货单>
1354: <订货单>
1355: <品名>真丝旗袍</品名>
1356: <单价>3,600</单价>
1357: <数量>2</数量>
1358: </订货单>
1359: </客户>
1360: <客户 姓名='董巧巧' 年龄='19'>
1361: <职务>乖巧人儿</职务>
1362: <电话>029*-981256**</电话>
1363: <订货单>
1364: <品名>旺角酒楼</品名>
1365: <单价>2,500,000</单价>
1366: <数量>1</数量>
1367: </订货单>
1368: <订货单>
1369: <品名>奥迪TT</品名>
1370: <单价>650,000</单价>
1371: <数量>1</数量>
1372: </订货单>
1373: </客户>
1374: <客户 姓名='萧玉霜' 年龄='17'>
1375: <职务>萧家二小姐</职务>
1376: <电话>053*-985690**</电话>
1377: </客户>
1378: <客户 姓名='秦仙儿' 年龄='20'>
1379: <职务>霓裳公主</职务>
1380: <电话>023*-338987**</电话>
1381: <订货单>
1382: <品名>独门四合院</品名>
1383: <单价>12,000,000</单价>
1384: <数量>1</数量>
1385: </订货单>
1386: </客户>
1387: <客户 姓名='萧玉若' 年龄='21'>
1388: <职务>萧家大小姐</职务>
1389: <电话>035*-120967**</电话>
1390: </客户>
1391: <客户 姓名='洛凝' 年龄='19'>
1392: <职务>金陵才女</职务>
1393: <电话>033*-985690**</电话>
1394: </客户>
1395: </通讯录>";
1396:
1397: XElement root = XElement.Parse(sxml);
1398:
1399: //统计结果
1400: var count = from item in root.Elements("客户")
1401: let cc = (from l in item.Elements("订货单") let c = Convert.ToDouble(l.Element("单价").Value) * (double)l.Element("数量") select c).Sum()
1402: where cc > 0
1403: select new { Count = cc, Node = item };
1404:
1405: ///变造新的XML树
1406: XElement newroot = new XElement
1407: (
1408: "客户订单表",
1409: new XElement("订单总价", count.Sum(item => item.Count).ToString("c")),
1410: new XElement("订户总数", count.Count()),
1411: new XElement("明细",
1412: (from i in count
1413: select new XElement(i.Node.Name, i.Node.Attribute("姓名"),
1414: new XAttribute("电话", i.Node.Element("电话").Value),
1415: new XAttribute("小计", i.Count.ToString("c")),
1416: (from p in i.Node.Elements("订货单") select new XElement("订货", from l in p.Elements() select new XAttribute(l.Name, l.Value)))))
1417: )
1418: );
1419:
1420: Console.WriteLine(newroot);
1421:
1422: Console.ReadKey();
1423: }
1424: }
1425: }
1426:
1427: using System;
1428: using System.Linq;
1429: using System.Xml.Linq;
1430:
1431: namespace DemoTransforming2
1432: {
1433: class Program
1434: {
1435: static void Main(string[] args)
1436: {
1437: string sxml = @"<数据>
1438: <字>你 赵 月 钱 李 王 孙 喜 晨 曦 我 凡 宝 悦 爱</字>
1439: <数>2 3 4 5 6 7</数>
1440: <颜色>粉 绿 黄 兰</颜色>
1441: <其他>蛋糕 妈妈 衣服</其他>
1442: </数据>";
1443:
1444: XElement root = XElement.Parse(sxml);
1445:
1446: ///变造新的XML树
1447: XElement newroot = new XElement
1448: (
1449: new XElement("我的宝贝",
1450: new XElement("姓名",
1451: string.Format("{0}{1}{2}",
1452: root.Element("字").Value.Split(' ').ElementAt(5),
1453: root.Element("字").Value.Split(' ').ElementAt(9),
1454: root.Element("字").Value.Split(' ').ElementAt(13))),
1455: new XElement("乳名",
1456: string.Format("{0}{1}",
1457: root.Element("字").Value.Split(' ').ElementAt(2),
1458: root.Element("字").Value.Split(' ').ElementAt(2))),
1459: new XElement("年龄",
1460: string.Format("{0}岁",
1461: root.Element("数").Value.Split(' ').ElementAt(1))),
1462: new XElement("喜欢的颜色",
1463: string.Format("{0}色",
1464: root.Element("颜色").Value.Split(' ').First())),
1465: new XElement("喜欢的食物",
1466: root.Element("其他").Value.Split(' ').First()),
1467: new XElement("最喜欢的人",
1468: root.Element("其他").Value.Split(' ').ElementAt(1)),
1469: new XElement("经常说的话",
1470: string.Format("{0}{1}{2}{3}",
1471: root.Element("其他").Value.Split(' ').ElementAt(1),
1472: root.Element("字").Value.Split(' ').ElementAt(10),
1473: root.Element("字").Value.Split(' ').Last(),
1474: root.Element("字").Value.Split(' ').First())),
1475: new XElement("依恋物",
1476: string.Format("{0}{1}",
1477: root.Element("其他").Value.Split(' ').ElementAt(1),
1478: root.Element("其他").Value.Split(' ').Last()))
1479: )
1480: );
1481:
1482:
1483: Console.WriteLine(newroot);
1484:
1485: Console.ReadKey();
1486:
1487: }
1488: }
1489: }
1490:
1491:
1492: ////// <summary>
1493: /// 利用XML中XDocument重载函数ToString输出XML节点到字符串
1494: /// </summary>
1495:
1496: using System;
1497: using System.IO;
1498: using System.Xml.Linq;
1499:
1500: namespace DemoOutputString
1501: {
1502: class Program
1503: {
1504: static void Main(string[] args)
1505: {
1506: XNamespace sp = "http://www.tiyor.com";
1507:
1508: XElement root = new XElement(sp + "根元素",
1509: new XAttribute("属性", "0")
1510: );
1511:
1512: XDocument doc = new XDocument(
1513: new XDeclaration("1.0","utf-16","yes"),
1514: new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
1515: new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
1516: new XComment("这是文档的注释内容"), root);
1517:
1518:
1519: root.Add(new XElement(sp + "子元素"),
1520: new XElement(sp + "子元素")
1521: );
1522:
1523: root.Add(new XCData("这里是根元素的CDATA节点"));
1524:
1525: StringWriter strw = new StringWriter();
1526: doc.Save(strw, SaveOptions.None);
1527: strw.Close();
1528:
1529: string strxml = strw.ToString();
1530:
1531: Console.WriteLine(strxml);
1532:
1533: Console.ReadKey();
1534: }
1535: }
1536: }
1537:
1538: ////// <summary>
1539: /// TextWriter
1540: /// </summary>
1541:
1542:
1543: using System;
1544: using System.Xml.Linq;
1545:
1546: namespace DemoOutputTextWriter
1547: {
1548: class Program
1549: {
1550: static void Main(string[] args)
1551: {
1552: XNamespace sp = "http://www.tiyor.com";
1553:
1554: XElement root = new XElement(sp + "根元素",
1555: new XAttribute("属性", "0")
1556: );
1557:
1558: XDocument doc = new XDocument(
1559: new XDeclaration("1.0", "utf8", "yes"),
1560: new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
1561: new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
1562: new XComment("这是文档的注释内容"), root);
1563:
1564:
1565: root.Add(new XElement(sp + "子元素"),
1566: new XElement(sp + "子元素")
1567: );
1568:
1569: root.Add(new XCData("这里是根元素的CDATA节点"));
1570:
1571: doc.Save(Console.Out, SaveOptions.None);
1572: Console.ReadKey();
1573: }
1574: }
1575: }
1576:
1577:
1578: ////// <summary>
1579: /// 输出XML树倒文件
1580: /// </summary>
1581:
1582:
1583: using System.Xml;
1584: using System.Xml.Linq;
1585:
1586: namespace DemoOutputFile
1587: {
1588: class Program
1589: {
1590: static void Main(string[] args)
1591: {
1592: XNamespace sp = "http://www.tiyor.com";
1593:
1594: XElement root = new XElement(sp + "根元素",
1595: new XAttribute("属性", "0")
1596: );
1597:
1598: XDocument doc = new XDocument(
1599: new XDeclaration("1.0", "utf8", "yes"),
1600: new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
1601: new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
1602: new XComment("这是文档的注释内容"), root);
1603:
1604:
1605: root.Add(new XElement(sp + "子元素"),
1606: new XElement(sp + "子元素")
1607: );
1608:
1609: root.Add(new XCData("这里是根元素的CDATA节点"));
1610:
1611:
1612: doc.Save("test1.xml", SaveOptions.None);
1613: XmlWriter xw = XmlWriter.Create("test2.xml");
1614: doc.WriteTo(xw);
1615: xw.Close();
1616:
1617: }
1618: }
1619: }
1620:
1621:
1622:
1623:
1624: