dotnet-snippets.de
Willkommen bei dotnet-snippets.de! Snippet hinzufügen Login Registrieren
Snippets in der Datenbank: 1405 | Anzahl registrierter User: 1436 | Besucher online: 35
Hauptmenü
Home
Top Ten
Zufälliger Snippet
Tech-Ed-Gewinnspiel
FAQs
.NET Community
dotnet-forum.de
dotnet-kicks.de
Social

RSS Feeds
Rss Alle Snippets
Rss C#
Rss VB.NET
Rss C++
Rss ASP.NET
Partner
Partner von Codezone.de


Member of Microsoft Community Leader/Insider Program (CLIP)

XMLIO - einfachstes (De)serialisieren von/zu XML-Dateien


Autor: Rainer Hilmer
Sprache: C#
Bewertung: 8,2
(1 Bewertung)

Anzahl der Aufrufe: 2417
  

Beschreibung:

Das Jonglieren mit XElements ist nicht nur nervtötend umständlich, sondern auch statisch. XmlSerializer hat auch so seine Tücken. Mit XMLIO wird das Speichern und Laden von Daten in XML Dateien zum Kinderspiel. Ein kleines Demo findet ihr im XML-Kommentar zur Klasse. Eine ausführliche Anleitung mit weiteren Beispielen gibt es als PDF-Dokument (englisch) hier (XMLIO ist Bestandteil meines DotNetExpansions Framework):
http://cyrons.beanstalkapp.com/general/browse/DotNetExpansions/tags/(neueste Release Nummer)/

Weitere Informationen zum DotNetExpansions Framework gibt es hier:
http://dotnet-forum.de/blogs/rainerhilmer/archive/2009/09/28/dotnet-expansions-framework.aspx


Abgelegt unter: XML.



C#
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
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace DotNetExpansions.IO
{
   /// <summary>
   /// Vereinfacht das Laden, Validieren und Speichern von XML-Dateien.
   /// </summary>
   /// <remarks>
   /// The first example uses a simple business object.
   /// The second example uses a complex business object with nested object.
   /// The third example shows the use of XmlIo with a dictionary
   ///  which holds values of different types.
   ///  Note: The use of such a configuration technique is not recommended
   ///  but XmlIo is able to handle even that.
   /// The fourth example shows the usage of XSD validation with the same simple business object
   ///  from the first sample.
   /// </remarks>
   /// <example>
   /// This demo shows the use of XmlIo with a very simple business object.
   /// <code>
   /// <![CDATA[
   /// namespace SimpleConfigDemo
   /// {
   ///    public class SimpleConfig
   ///    {
   ///       public byte Dimensions { get; set; }
   ///       public int HyperspaceEntrySection { get; set; }
   ///       public string NanobotsEmitterName { get; set; }
   ///       public string PicobotControllerIP { get; set; }
   ///       public float WarpFactor { get; set; }
   ///    }
   /// }
   /// ]]>
   /// </code>
   /// </example>
   ///
   /// <example>
   /// <code>
   /// <![CDATA[
   /// using System;
   /// using System.Windows.Forms;
   /// using DotNetExpansions;
   /// 
   /// namespace SimpleConfigDemo
   /// {
   ///    class Program
   ///    {
   ///       static void Main()
   ///       {
   ///          var configManager = new XmlIo(Path.Combine(Environment.CurrentDirectory, "DemoConfig.xml"));
   ///          SimpleConfig config = CreateConfig();
   ///          Console.WriteLine("Saving Configuration...");
   ///          configManager.Save(config);
   ///          Console.WriteLine("Press any key to load the configuration."
   ///                            + Environment.NewLine);
   ///          Console.ReadKey();
   /// 
   ///          // Destroy the previously instantiated data transfer object for demonstration purposes.
   ///          config = null;
   ///          Console.WriteLine("Now loading the configuration..."
   ///                            + Environment.NewLine);
   ///          config = configManager.Load<SimpleConfig>();
   ///          ShowConfig(config);
   /// 
   ///          // Verhindert das selbsttätige Schließen des Konsolenfensters.
   ///          Console.WriteLine("\nPress any key to terminate the program.");
   ///          Console.ReadKey();
   ///       }
   /// 
   ///       private static SimpleConfig CreateConfig()
   ///       {
   ///          var config = new SimpleConfig();
   ///          config.Dimensions = 7;
   ///          config.HyperspaceEntrySection = 1;
   ///          config.NanobotsEmitterName = "MyNanobotsEmitter";
   ///          config.PicobotControllerIP = "127.0.0.1";
   ///          config.WarpFactor = 10.0f;
   ///          return config;
   ///       }
   /// 
   ///       private static void ShowConfig(SimpleConfig config)
   ///       {
   ///          Console.WriteLine("Nanobots EmitterName: {0}", config.NanobotsEmitterName);
   ///          Console.WriteLine("Picobot Controller IP: {0}", config.PicobotControllerIP);
   ///          Console.WriteLine("Dimensions: {0}", config.Dimensions);
   ///          Console.WriteLine("Hyperspace Entry Section: {0}", config.HyperspaceEntrySection);
   ///          Console.WriteLine("Warp Factor: {0}", config.WarpFactor);
   ///       }
   ///    }
   /// }
   /// 
   /// /* Output:
   /// Saving Configuration...
   /// Press any key to load the configuration.
   /// 
   /// Now loading the configuration...
   /// 
   /// Nanobots EmitterName: MyNanobotsEmitter
   /// Picobot Controller IP: 127.0.0.1
   /// Dimensions: 7
   /// Hyperspace Entry Section: 1
   /// Warp Factor: 10
   /// 
   /// Press any key to terminate the program.
   /// */
   /// ]]>
   /// </code>
   /// </example>
   /// This demo generates te following XML file.
   /// <example>
   /// <code>
   /// <![CDATA[
   /// <SimpleConfig xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/SimpleConfigDemo">
   ///    <Dimensions>7</Dimensions>
   ///    <HyperspaceEntrySection>1</HyperspaceEntrySection>
   ///    <NanobotsEmitterName>MyNanobotsEmitter</NanobotsEmitterName>
   ///    <PicobotControllerIP>127.0.0.1</PicobotControllerIP>
   ///    <WarpFactor>10</WarpFactor>
   /// </SimpleConfig>
   /// ]]>
   /// </code>
   /// </example>
   /// <example>
   /// This demo shows the use of XmlIo with a complex business object which contains nested objects.
   /// <code>
   /// <![CDATA[
   /// using System.Drawing;
   /// 
   /// namespace NestedConfigDemo
   /// {
   ///    public class NestedConfig
   ///    {
   ///       public string MachineName { get; set; }
   ///       public UiConfig UiSettings { get; set; }
   ///       public UserConfig UserSettings { get; set; }
   ///       public DalConfig DalSettings { get; set; }
   /// 
   ///       public class UiConfig
   ///       {
   ///          public Size WindowSize { get; set; }
   ///          public Point WindowLocation { get; set; }
   ///          public Color BackgroundColor { get; set; }
   ///          public Color TextColor { get; set; }
   ///       }
   /// 
   ///       public class UserConfig
   ///       {
   ///          public string FirstName { get; set; }
   ///          public string LastName { get; set; }
   ///          public string Email { get; set; }
   ///       }
   /// 
   ///       public class DalConfig
   ///       {
   ///          public string ConnectionString { get; set; }
   ///       }
   ///    }
   /// }
   /// ]]>
   /// </code>
   /// </example>
   ///
   /// <example>
   /// <code>
   /// <![CDATA[
   /// using DotNetExpansions;
   /// 
   /// namespace NestedConfigDemo
   /// {
   ///    using System;
   ///    using System.Drawing;
   ///    using System.Windows.Forms;
   /// 
   ///    class Program
   ///    {
   ///       static void Main()
   ///       {
   ///          var configManager =
   ///          new XmlIo(Path.Combine(Environment.CurrentDirectory, "DemoConfig.xml");
   ///          NestedConfig config = CreateConfig();
   ///          configManager.Save(config);
   ///          config = null;
   /// 
   ///          try
   ///          {
   ///             config = configManager.Load<NestedConfig>();
   ///             ShowConfig(config);
   ///          }
   ///          catch(InvalidOperationException problem)
   ///          {
   ///             Console.WriteLine(problem.Message);
   ///             Console.WriteLine(problem.Data);
   ///          }
   /// 
   ///          // Verhindert das selbsttätige Schließen des Konsolenfensters.
   ///          Console.WriteLine("\nPress any key to terminate the program.");
   ///          Console.ReadKey();
   ///       }
   /// 
   ///       private static NestedConfig CreateConfig()
   ///       {
   ///          var config = new NestedConfig();
   ///          config.DalSettings = new NestedConfig.DalConfig
   ///          {
   ///             ConnectionString = "Some Connection string"
   ///          };
   ///          config.MachineName = "MyComputer";
   ///          config.UiSettings = new NestedConfig.UiConfig
   ///          {
   ///             BackgroundColor = Color.White,
   ///             TextColor = Color.FromArgb(128, 0, 255),
   ///             WindowLocation = new Point(200, 100),
   ///             WindowSize = new Size(640, 480)
   ///          };
   ///          config.UserSettings = new NestedConfig.UserConfig
   ///          {
   ///             Email = "none@yourbusiness.com",
   ///             FirstName = "Santa",
   ///             LastName = "Claus"
   ///          };
   ///          return config;
   ///       }
   /// 
   ///       private static void ShowConfig(NestedConfig config)
   ///       {
   ///          Console.WriteLine("Connection string: {0}", config.DalSettings.ConnectionString);
   ///          Console.WriteLine("Machine name: {0}", config.MachineName);
   ///          Console.WriteLine("Background color: {0}", config.UiSettings.BackgroundColor);
   ///          Console.WriteLine("Text color: {0}", config.UiSettings.TextColor);
   ///          Console.WriteLine("Window location: {0}", config.UiSettings.WindowLocation);
   ///          Console.WriteLine("Window size: {0}", config.UiSettings.WindowSize);
   ///          Console.WriteLine("First name: {0}", config.UserSettings.FirstName);
   ///          Console.WriteLine("Last name: {0}", config.UserSettings.LastName);
   ///          Console.WriteLine("Email address: {0}", config.UserSettings.Email);
   ///       }
   ///    }
   /// }
   /// /* Output
   /// Connection string: Some Connection string
   /// Machine name: MyComputer
   /// Background color: Color [White]
   /// Text color: Color [A=255, R=128, G=0, B=255]
   /// Window location: {X=200,Y=100}
   /// Window size: {Width=640, Height=480}
   /// First name: Santa
   /// Last name: Claus
   /// Email address: none@yourbusiness.com
   /// 
   /// Press any key to terminate the program.
   /// */
   /// ]]>
   /// </code>
   /// </example>
   /// <example>
   /// This demo creates the following XML file.
   /// <code>
   /// <![CDATA[
   /// <NestedConfig xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/NestedConfigDemo">
   ///   <DalSettings>
   ///     <ConnectionString>Some Connection string</ConnectionString>
   ///   </DalSettings>
   ///   <MachineName>MyComputer</MachineName>
   ///   <UiSettings>
   ///     <BackgroundColor xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Drawing">
   ///       <d3p1:knownColor>164</d3p1:knownColor>
   ///       <d3p1:name i:nil="true" />
   ///       <d3p1:state>1</d3p1:state>
   ///       <d3p1:value>0</d3p1:value>
   ///     </BackgroundColor>
   ///     <TextColor xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Drawing">
   ///       <d3p1:knownColor>0</d3p1:knownColor>
   ///       <d3p1:name i:nil="true" />
   ///       <d3p1:state>2</d3p1:state>
   ///       <d3p1:value>4286578943</d3p1:value>
   ///     </TextColor>
   ///     <WindowLocation xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Drawing">
   ///       <d3p1:x>200</d3p1:x>
   ///       <d3p1:y>100</d3p1:y>
   ///     </WindowLocation>
   ///     <WindowSize xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Drawing">
   ///       <d3p1:height>480</d3p1:height>
   ///       <d3p1:width>640</d3p1:width>
   ///     </WindowSize>
   ///   </UiSettings>
   ///   <UserSettings>
   ///     <Email>none@yourbusiness.com</Email>
   ///     <FirstName>Santa</FirstName>
   ///     <LastName>Claus</LastName>
   ///   </UserSettings>
   /// </NestedConfig>
   /// ]]>
   /// </code>
   /// </example>
   /// <example>
   /// This demo shows the use of XmlIo with a dictionary which holds values of different types. Note: The use of such a configuration technique is not recommended but XmlIo is able to handle even that.
   /// <code>
   /// <![CDATA[
   /// // In case someone uses this kind of configuration storage (which is not recommended).
   /// using System.Collections.Generic;
   /// using System.Drawing;
   /// using System.Runtime.Serialization;
   /// 
   /// namespace ConfigListDemo
   /// {
   ///    [KnownType(typeof(Point))]
   ///    [KnownType(typeof(Size))]
   ///    [KnownType(typeof(Color))]
   ///    public class ConfigDictionary
   ///    {
   ///       public ConfigDictionary()
   ///       {
   ///          if(Configuration == null)
   ///             Configuration = new Dictionary<string, object>();
   ///       }
   /// 
   ///       public Dictionary<string, object> Configuration { get; set; }
   ///    }
   /// }
   /// ]]>
   /// </code>
   /// </example>
   ///
   /// <example>
   /// <code>
   /// <![CDATA[
   /// using System;
   /// using System.Drawing;
   /// using System.Windows.Forms;
   /// using DotNetExpansions;
   /// 
   /// namespace ConfigListDemo
   /// {
   ///    class Program
   ///    {
   ///       static void Main()
   ///       {
   ///          var yourConfig = CreateConfig();
   ///          var xmlIo = new XmlIo(Path.Combine(Environment.CurrentDirectory, "YourConfig.xml");
   ///          Console.WriteLine("Saving configuration");
   ///          xmlIo.Save(yourConfig);
   ///          yourConfig = null;
   ///          try
   ///          {
   ///             Console.WriteLine("Trying to load your config data...");
   ///             yourConfig = xmlIo.Load<ConfigDictionary>();
   ///             ShowConfig(yourConfig);
   ///          }
   ///          catch(InvalidOperationException problem)
   ///          {
   ///             Console.WriteLine(problem.Message);
   ///             Console.WriteLine(problem.Data);
   ///          }
   /// 
   ///          // Verhindert das selbsttätige Schließen des Konsolenfensters.
   ///          Console.WriteLine("\nPress any key to terminate the program.");
   ///          Console.ReadKey();
   ///       }
   /// 
   ///       private static ConfigDictionary CreateConfig()
   ///       {
   ///          var config = new ConfigDictionary();
   ///          config.Configuration.Add("Integer", 1);
   ///          config.Configuration.Add("Double", 3.141592654);
   ///          config.Configuration.Add("String", "Hello world");
   ///          config.Configuration.Add("Point", new Point(100, 200));
   ///          config.Configuration.Add("Size", new Size(1024, 768));
   ///          config.Configuration.Add("RGB-color", Color.FromArgb(128, 0, 255));
   ///          config.Configuration.Add("named color", Color.Fuchsia);
   ///          return config;
   ///       }
   /// 
   ///       private static void ShowConfig(ConfigDictionary configDictionary)
   ///       {
   ///          foreach(var keyValuePair in configDictionary.Configuration)
   ///          {
   ///             Console.WriteLine("Your {0}: {1}", keyValuePair.Key, keyValuePair.Value);
   ///          }
   ///       }
   ///    }
   /// }
   /// /* Output:
   /// Saving configuration
   /// Trying to load your config data...
   /// Your Integer: 1
   /// Your Double: 3,141592654
   /// Your String: Hello world
   /// Your Point: {X=100,Y=200}
   /// Your Size: {Width=1024, Height=768}
   /// Your RGB-color: Color [A=255, R=128, G=0, B=255]
   /// Your named color: Color [Fuchsia]
   /// 
   /// Press any key to terminate the program.
   /// */
   /// ]]>
   /// </code>
   /// </example>
   /// <example>
   /// This demo creates the following XML file.
   /// <code>
   /// <![CDATA[
   /// <ConfigDictionary xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/ConfigListDemo">
   ///   <Configuration xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
   ///     <d2p1:KeyValueOfstringanyType>
   ///       <d2p1:Key>Integer</d2p1:Key>
   ///       <d2p1:Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:int">1</d2p1:Value>
   ///     </d2p1:KeyValueOfstringanyType>
   ///     <d2p1:KeyValueOfstringanyType>
   ///       <d2p1:Key>Double</d2p1:Key>
   ///       <d2p1:Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:double">3.141592654</d2p1:Value>
   ///     </d2p1:KeyValueOfstringanyType>
   ///     <d2p1:KeyValueOfstringanyType>
   ///       <d2p1:Key>String</d2p1:Key>
   ///       <d2p1:Value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string">Hello world</d2p1:Value>
   ///     </d2p1:KeyValueOfstringanyType>
   ///     <d2p1:KeyValueOfstringanyType>
   ///       <d2p1:Key>Point</d2p1:Key>
   ///       <d2p1:Value xmlns:d4p1="http://schemas.datacontract.org/2004/07/System.Drawing" i:type="d4p1:Point">
   ///         <d4p1:x>100</d4p1:x>
   ///         <d4p1:y>200</d4p1:y>
   ///       </d2p1:Value>
   ///     </d2p1:KeyValueOfstringanyType>
   ///     <d2p1:KeyValueOfstringanyType>
   ///       <d2p1:Key>Size</d2p1:Key>
   ///       <d2p1:Value xmlns:d4p1="http://schemas.datacontract.org/2004/07/System.Drawing" i:type="d4p1:Size">
   ///         <d4p1:height>768</d4p1:height>
   ///         <d4p1:width>1024</d4p1:width>
   ///       </d2p1:Value>
   ///     </d2p1:KeyValueOfstringanyType>
   ///     <d2p1:KeyValueOfstringanyType>
   ///       <d2p1:Key>RGB-color</d2p1:Key>
   ///       <d2p1:Value xmlns:d4p1="http://schemas.datacontract.org/2004/07/System.Drawing" i:type="d4p1:Color">
   ///         <d4p1:knownColor>0</d4p1:knownColor>
   ///         <d4p1:name i:nil="true" />
   ///         <d4p1:state>2</d4p1:state>
   ///         <d4p1:value>4286578943</d4p1:value>
   ///       </d2p1:Value>
   ///     </d2p1:KeyValueOfstringanyType>
   ///     <d2p1:KeyValueOfstringanyType>
   ///       <d2p1:Key>named color</d2p1:Key>
   ///       <d2p1:Value xmlns:d4p1="http://schemas.datacontract.org/2004/07/System.Drawing" i:type="d4p1:Color">
   ///         <d4p1:knownColor>73</d4p1:knownColor>
   ///         <d4p1:name i:nil="true" />
   ///         <d4p1:state>1</d4p1:state>
   ///         <d4p1:value>0</d4p1:value>
   ///       </d2p1:Value>
   ///     </d2p1:KeyValueOfstringanyType>
   ///   </Configuration>
   /// </ConfigDictionary>
   /// ]]>
   /// </code>
   /// </example>
   /// <example>
   /// This last example shows the usage of the XSD validation with the same simple business object from the first sample.
   /// <code>
   /// <![CDATA[
   /// using System;
   /// using System.Windows.Forms;
   /// using DotNetExpansions;
   /// 
   /// namespace SchemaValidationDemo
   /// {
   ///    class Program
   ///    {
   ///       static void Main()
   ///       {
   ///          var configManager =
   ///             new XmlIo(Path.Combine(Environment.CurrentDirectory, "DemoConfig.xml");
   /// 
   ///          var config = new SimpleConfig();
   ///          config.Dimensions = 7;
   ///          config.HyperspaceEntrySection = 1;
   ///          config.NanobotsEmitterName = "MyNanobotsEmitter";
   ///          config.PicobotControllerIP = "127.0.0.1";
   ///          config.WarpFactor = 3.141592654;
   /// 
   ///          // Save config =========================================================
   /// 
   ///          Console.WriteLine("Saving Configuration...");
   ///          configManager.Save(config);
   ///          Console.WriteLine("Press any key to validate the configuration."
   ///                            + Environment.NewLine);
   ///          Console.ReadKey();
   /// 
   ///          // Validaion ===========================================================
   /// 
   ///          configManager.ValidationEvent += ConfigManagerValidationEvent;
   ///          ValidateConfig(configManager);
   ///          Console.WriteLine("Press any key to load the configuration."
   ///                         + Environment.NewLine);
   ///          Console.ReadKey();
   /// 
   ///          // Load config =========================================================
   /// 
   ///          // Destroy the previously instantiated data transfer object for demonstration purposes.
   ///          config = null;
   ///          Console.WriteLine("Now loading the configuration..."
   ///                            + Environment.NewLine);
   ///          try
   ///          {
   ///             config = configManager.Load<SimpleConfig>();
   ///             ShowConfig(config);
   ///          }
   ///          catch(InvalidOperationException problem)
   ///          {
   ///             Console.WriteLine(problem.Message);
   ///             Console.WriteLine(problem.Data);
   ///          }
   /// 
   ///          // Verhindert das selbsttätige Schließen des Konsolenfensters.
   ///          Console.WriteLine("\nPress any key to terminate the program.");
   ///          Console.ReadKey();
   ///       }
   /// 
   ///       private static void ValidateConfig(XmlIo configManager)
   ///       {
   ///          bool isValid = configManager.FileIsValidWith("DemoConfig.xsd");
   ///          if(isValid)
   ///             Console.WriteLine("XML-File is valid.");
   ///          else
   ///             Console.WriteLine("XML-File is invalid.");
   ///          return;
   ///       }
   /// 
   ///       static void ConfigManagerValidationEvent(object sender, System.Xml.Schema.ValidationEventArgs e)
   ///       {
   ///          Console.WriteLine(e.Severity + ": " + e.Message);
   ///       }
   /// 
   ///       private static void ShowConfig(SimpleConfig config)
   ///       {
   ///          Console.WriteLine("Nanobots EmitterName: {0}", config.NanobotsEmitterName);
   ///          Console.WriteLine("Picobot Controller IP: {0}", config.PicobotControllerIP);
   ///          Console.WriteLine("Dimensions: {0}", config.Dimensions);
   ///          Console.WriteLine("Hyperspace Entry Section: {0}", config.HyperspaceEntrySection);
   ///          Console.WriteLine("Warp Factor: {0}", config.WarpFactor);
   ///       }
   ///    }
   /// }
   /// 
   /// ]]>
   /// </code>
   /// </example>
   ///
   /// <example>
   /// This is the XSD file content for validation.
   /// <code>
   /// <![CDATA[
   /// <?xml version="1.0" encoding="utf-8"?>
   /// <xs:schema xmlns:i="http://www.w3.org/2001/XMLSchema-instance" attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://schemas.datacontract.org/2004/07/SchemaValidationDemo" xmlns:xs="http://www.w3.org/2001/XMLSchema">
   ///    <xs:element name="SimpleConfig">
   ///       <xs:complexType>
   ///          <xs:sequence>
   ///             <xs:element name="Dimensions" type="xs:unsignedByte" />
   ///             <xs:element name="HyperspaceEntrySection" type="xs:unsignedInt" />
   ///             <xs:element name="NanobotsEmitterName" type="xs:string" />
   ///             <xs:element name="PicobotControllerIP" type="xs:string" />
   ///             <xs:element name="WarpFactor" type="xs:double" />
   ///          </xs:sequence>
   ///       </xs:complexType>
   ///    </xs:element>
   /// </xs:schema>
   /// ]]>
   /// </code>
   /// </example>
   /// <seealso cref="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.knowntypeattribute.aspx"/>
   /// <seealso cref="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx"/>
   public class XmlIo
   {
      #region Fields

      private static bool fileIsValid = true;
      private string fullFilename;

      #endregion Fields
      #region Events

      /// <summary>
      /// Tritt bei einem Validationsfehler ein.
      /// </summary>
      public event ValidationEventHandler ValidationEvent;

      #endregion Events
      #region Constructors

      /// <summary>
      /// Initialisiert eine neue Instanz der <see cref="XmlIo"/> Klasse.
      /// </summary>
      /// <param name="fullFilename">Der voll qualifizierte Dateiname (Pfad mit Dateiname und Extension)</param>
      public XmlIo(string fullFilename)
      {
         if(IsValidFullFilename(fullFilename))
            this.fullFilename = fullFilename;
         else
            throw new ArgumentException("fullFilename is invalid");
      }

      /// <summary>
      /// Initialisiert eine neue Instanz der <see cref="XmlIo"/> Klasse.
      /// </summary>
      /// <param name="filepath">Der Dateipfad, unter dem die XML-Datei abgelegt werden soll.</param>
      /// <param name="filename">Der Name der XML-Datei inklusive Extension.</param>
      [Obsolete("Dieser Konstruktor existiert nur noch für die Abwärtskompatibilität.", false)]
      public XmlIo(string filepath, string filename)
      {
         Filepath = ValidateFilepath(filepath);
         Filename = ValidateFilename(filename);
         fullFilename = Path.Combine(filepath, filename);
      }

      #endregion Constructors
      #region Properties

      /// <summary>
      /// Gibt den Pfad zur XML-Datei zurück.
      /// </summary>
      public string Filepath { get; private set; }

      /// <summary>
      /// Gibt den Namen der XML-Datei zurück.
      /// </summary>
      public string Filename { get; private set; }

      #endregion
      #region Public Methods

      /// <summary>
      /// Lädt eine XML-Datei für ein beliebiges business object.
      /// </summary>
      /// <typeparam name="T">Der Typ des Business-Objekts.</typeparam>
      /// <returns>Das Business-Objekt</returns>
      public T Load<T>() where T : class
      {
         var filePermissions = new FileIOPermission(
            FileIOPermissionAccess.Read, fullFilename);
         filePermissions.Assert();

         var fs = new FileStream(fullFilename, FileMode.Open, FileAccess.Read);
         var reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
         var ser = new DataContractSerializer(typeof(T));
         var config = ser.ReadObject(reader);
         fs.Close();
         return config as T;
      }

      /// <summary>
      /// Speichert eine XML-Datei für ein beliebiges Business Object.
      /// </summary>
      /// <typeparam name="T">Der Typ des Business Objects (die Angabe ist optional).</typeparam>
      /// <param name="businessObject">Das Business Object</param>
      public void Save<T>(T businessObject) where T : class
      {
         var filePermissions = new FileIOPermission(
            FileIOPermissionAccess.Write, fullFilename);
         filePermissions.Assert();

         var writer = new XmlTextWriter(fullFilename, Encoding.UTF8);
         if(writer == null)
            throw new NullReferenceException();
         writer.Formatting = Formatting.Indented;
         var ser = new DataContractSerializer(businessObject.GetType());
         ser.WriteObject(writer, businessObject);
         writer.Close();
      }

      /// <summary>
      /// Validiert eine XML-Datei mittels der angegebenen XSD-Datei.
      /// </summary>
      /// <param name="validationSchemaFilename">Die XSD-Datei</param>
      /// <returns><c>true</c> wenn die XML-Datei gültig ist, anderenfalls <c>false</c>.</returns>
      public bool FileIsValidWith(string validationSchemaFilename)
      {
         var filePermissions = new FileIOPermission(
            FileIOPermissionAccess.Read, fullFilename);
         filePermissions.Assert();

         var xmlReaderSettings = new XmlReaderSettings();
         xmlReaderSettings.Schemas.Add(
            null, Path.Combine(Path.GetDirectoryName(fullFilename), validationSchemaFilename));
         xmlReaderSettings.ValidationType = ValidationType.Schema;
         xmlReaderSettings.ValidationEventHandler += XmlValidationEventHandler;
         var config = XmlReader.Create(fullFilename, xmlReaderSettings);
         while(config.Read()) { }
         xmlReaderSettings.CloseInput = true;
         return fileIsValid;
      }

      #endregion Public Methods
      #region Private Methods

      private static bool IsValidFullFilename(string fullFilename)
      {
         return !string.IsNullOrEmpty(fullFilename) && Directory.Exists(Path.GetDirectoryName(fullFilename));
      }

      private string ValidateFilename(string filename)
      {
         if(!IsValidEntry(filename))
            throw new ArgumentException();
         if(!filename.EndsWith(".xml"))
            throw new ArgumentException("Filename-extension is either missing or wrong. It must be .xml");
         this.Filename = filename;
         return filename;
      }

      private string ValidateFilepath(string filepath)
      {
         if(!IsValidPath(filepath))
            throw new DirectoryNotFoundException();
         if(filepath.EndsWith(@"\"))
            filepath = filepath.Substring(0, filepath.Length - 1);
         this.Filepath = filepath;
         return filepath;
      }

      private static bool IsValidEntry(string entry)
      {
         return !string.IsNullOrEmpty(entry);
      }

      private static bool IsValidPath(string path)
      {
         return Directory.Exists(path);
      }

      // Bubbling up the Event.
      private void XmlValidationEventHandler(object sender, ValidationEventArgs e)
      {
         fileIsValid = false;
         if(ValidationEvent != null)
            ValidationEvent(this, e);
      }

      #endregion Private Methods
   }
}
Sie haben Fragen zu diesem Snippet oder brauchen Hilfe bei der .NET Entwicklung?
Freundliche und kompetente Entwickler helfen Ihnen gern weiter im Forum für .NET Entwicklung.



Kommentare:
(Zum Schreiben von Kommentaren bitte anmelden.)



Diese Snippets könnten für Sie interessant sein:
[C#] Treeview in XML schreiben
[C#] Objekt in XML speichern (Serialisieren)
[ASP.net] XML - HTML Transformation
[C#] Generische XML-Serialisierung
[C#] CSV und XML-Datei Datenbank-Import (incl. valid-check)
[C#] Währungskurse in Datenbank speichern
[VB.NET] Einfaches Erstellen einer XML Datei in .Net
[C#] XML in DataTable laden
[C#] Intellisense Unterstützung für XML Dateien für LINQ
[C#] user.config und generische Listen
[C#] Dataset verschlüsseln
[C#] Xml Datei entschlüsseln
[VB.NET] Objekt mit dem XmlSerializer serialisieren
[VB.NET] XML Datei mit dem XmlSerializer deserialisieren
[ASP.net] XML Daten über einen Internet Proxy abfragen
[C#] XML-Programmkonfiguration / -Steuerung
[C#] Formatieren von Sonderzeichen für XML
[C#] Binärdatei in XML File speichern
[C#] Binärdatei aus XML Datei auslesen und abspeichern
[C#] leere Knoten aus XML Document entfernen
[C#] XML Kommentare entfernen
[C#] Austauch von kritischen Zeichen in einem String...
[C#] Excel-Export ohne Excel (auch für Web)
[C#] Ini-Datei-Klasse
[C#] TreeView Export To Xml OR Import from XMl
[C#] Autom. Laden & Speichern von Position und Größe eines Forms
[VB.NET] Bild als XML Datei Speichern
[C#] Ein Object serialisieren
[C#] Ein Object deserialisieren
[C#] XML Encoding eines XmlDocument ändern
[C#] XMLDocument in XDocument konvertieren
[C#] Rss Feed in XMLDocument laden
[VB.NET] XML Datei in DataSet einlesen
[C#] Image zu Base64 konvertieren und zurück
[C#] Konvertiert Code nach Example für XML-Kommentar
[C#] Generisch XML De-/ Serialisieren
[C#] XML generieren mit Linq to XML
[C#] 3 arten der Serialisierung bzw Deserialisierung
[C#] Spracherkennung
[C#] Wunderground Wettervorhersage

schlecht sehr gut
1 2 3 4 5 6 7 8 9 10
Nur angemeldete User können Snippets bewerten.