-
Notifications
You must be signed in to change notification settings - Fork 0
/
XElementExtensions.cs
820 lines (773 loc) · 27.9 KB
/
XElementExtensions.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
// Copyright SeaRisen LLC
// You may use this code without restrictions, but keep the copyright notice with this code.
// This file is found at: https://github.com/ChuckSavage/XmlLib
// If you find this code helpful and would like to donate, please consider purchasing one of
// the products at http://products.searisen.com, thank you.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
namespace XmlLib
{
/// <summary>
/// XElement extension methods.
/// </summary>
public static class XElementExtensions
{
public const bool ATTRIBUTE = true;
public const bool ELEMENT = false;
#region GetAttribute
/// <summary>
/// An attribute with the same namespace as the source will be null if it doesn't
/// specify the namespace abbreviation.
/// </summary>
public static XAttribute GetAttribute(this XElement source, string name)
{
if (source.HasAttributes)
return GetAttribute(source, source.ToXName(name));
return null;
}
/// <summary>
/// An attribute with the same namespace as the source will be null if it doesn't
/// specify the namespace abbreviation.
/// </summary>
public static XAttribute GetAttribute(this XElement source, XName name)
{
if (source.HasAttributes)
{
XAttribute result = source.Attribute(name);
if (null == result && (name.Namespace == source.Name.Namespace))
result = source.Attribute(name.LocalName);
return result;
}
return null;
}
#endregion
#region GetElement
/// <summary>
/// Get child element, create it if it doesn't exist in source.
/// </summary>
/// <param name="name">The tag name of the XElement.</param>
/// <returns>XElement found or created.</returns>
public static XElement GetElement(this XElement source, XName name)
{
XElement xe = null;
if (source.HasElements)
{
xe = source.Element(name);
if (null == xe) // get first node that matches by tag name (if one exists)
xe = source.Elements()
.FirstOrDefault(x => x.Name.LocalName == name.LocalName);
}
if (null == xe)
source.Add(xe = new XElement(name));
return xe;
}
/// <summary>
/// Get child element, create it if it doesn't exist in source.
/// </summary>
/// <param name="name">The tag name of the XElement.</param>
/// <returns>XElement found or created.</returns>
public static XElement GetElement(this XElement source, string name)
{
if (name.Contains('/') || name.Contains('\\'))
return Path(source, name);
return GetElement(source, ToXName(source, name));
}
/// <summary>
/// Get child elements.
/// </summary>
/// <param name="name">The tag name of the XElement.</param>
/// <returns>XElement found or created.</returns>
public static IEnumerable<XElement> GetElements(this XElement source, XName name)
{
if (source.HasElements)
{
if (null == name)
return source.Elements();
IEnumerable<XElement> elements = source.Elements(name);
if (0 == elements.Count())
elements = source.Elements()
.Where(x => x.Name.LocalName == name.LocalName);
return elements;
}
return new XElement[] { };
}
/// <summary>
/// Get child elements.
/// </summary>
/// <param name="name">The tag name of the XElement.</param>
/// <returns>XElement found or created.</returns>
public static IEnumerable<XElement> GetElements(this XElement source, string name)
{
if (source.HasElements)
{
if (string.IsNullOrEmpty(name))
return source.Elements();
source = NameCheck(source, name, out name);
return GetElements(source, ToXName(source, name));
}
return new XElement[] { };
}
/// <summary>
/// Get descendant elements.
/// </summary>
/// <param name="name">The tag name of the XElement.</param>
/// <returns>XElement found or created.</returns>
public static IEnumerable<XElement> GetDescendants(this XElement source, XName name)
{
if (null == name)
return source.Descendants();
IEnumerable<XElement> elements = source.Descendants(name);
if (0 == elements.Count())
elements = source.Descendants()
.Where(x => x.Name.LocalName == name.LocalName);
return elements;
}
/// <summary>
/// Get descendant elements.
/// </summary>
/// <param name="name">The tag name of the XElement.</param>
/// <returns>XElement found or created.</returns>
public static IEnumerable<XElement> GetDescendants(this XElement source, string name)
{
if (string.IsNullOrEmpty(name))
return source.Descendants();
source = NameCheck(source, name, out name);
return GetDescendants(source, ToXName(source, name));
}
/// <summary>
/// Try and get the element specified by the name path,
/// if it exists return true and out the value.
/// </summary>
public static bool TryGetElement
(
this XElement source,
string name,
out XElement value
)
{
try
{
value = Path(source, name, false);
return true;
}
catch (ArgumentOutOfRangeException)
{
value = null;
return false;
}
}
#endregion
#region GetString
/// <summary>
/// Get STRING of element/attribute
/// </summary>
public static string GetString
(
this XElement source,
XName name,
string defaultValue
)
{
if (null == source)
return defaultValue;
string result;
if (null == name)
result = (string)source;
else
{
result = (string)GetAttribute(source, name);
if (null == result)
result = (string)source.Element(name);
}
if (null == result)
result = defaultValue;
return result;
}
/// <summary>
/// Get STRING of element/attribute
/// </summary>
public static string GetString
(
this XElement source,
string name,
string defaultValue
)
{
source = NameCheck(source, name, out name);
return GetString(source, ToXName(source, name), defaultValue);
}
#endregion
#region Get
/// <summary>
/// Generic Get for a type.
/// <remarks>
/// It works as long as there is a converter for the type to
/// convert from string.
/// </remarks>
/// </summary>
/// <returns>The element converted to its type or the default
/// if it didn't exist or was empty.</returns>
public static T Get<T>(this XElement source, XName name, T @default)
{
T value;
string sValue = GetString(source, name, null);
if (string.IsNullOrEmpty(sValue))
return @default;
if (ConverterCache<T>.TryParse(sValue, out value))
return value;
if (ParseCache<T>.TryParse(sValue, out value))
return value;
if (ConstructorCache<T>.TryInvoke(source, sValue, out value))
return value;
// Throwing an exception helps you improve your parsing if the default
// methods provided by the type creator are not sufficient. You can
// create a constructor for your class or a parsing class for types that
// will handle the string value or the XElement itself.
throw new NotSupportedException("Can't parse XElement value to type:" + typeof(T).Name);
//return @default;
}
/// <summary>
/// Generic Get for a type.
/// <remarks>
/// It works as long as there is a converter for the type to convert
/// from string.
/// </remarks>
/// </summary>
/// <returns>The element converted to its type or the default if it
/// didn't exist or was empty.</returns>
public static T Get<T>(this XElement source, string name, T @default)
{
source = NameCheck(source, name, out name);
return Get(source, ToXName(source, name), @default);
}
// If TypeConverter is unavailable (aka Windows Phone 7),
/// <summary>
/// Store converters for a quicker lookup.
/// <remarks>
/// Saves about 3 MS (averaged) on ~3000 Get()'s
/// run 1000 times.
/// </remarks>
/// </summary>
private static class ConverterCache<T>
{
public static bool TryParse(string sValue, out T value)
{
value = default(T);
// If TypeConverter is unavailable (aka Windows Phone 7),
#if !WindowsPhone7
try
{
value = (T)Converter.ConvertFromString(sValue);
return true;
}
catch (NotSupportedException)
{ }
#endif
return false;
}
#if !WindowsPhone7
public static readonly TypeConverter Converter;
static ConverterCache()
{ Converter = TypeDescriptor.GetConverter(typeof(T)); }
#endif
}
#endregion
#region Set
/// <summary>
/// Set any value via its .ToString() method.
/// <para>
/// Returns XElement of source or the new XElement if is an ELEMENT
/// </para>
/// </summary>
/// <param name="isAttribute">
/// Use ATTRIBUTE or ELEMENT for clarity
/// </param>
/// <returns>source or XElement value</returns>
public static XElement Set
(
this XElement source,
string name,
object value,
bool isAttribute
)
{
return Set(source, name, value, isAttribute, false);
}
/// <summary>
/// Set any value via its .ToString() method.
/// <para>
/// Returns XElement of source or the new XElement if is an ELEMENT
/// </para>
/// </summary>
/// <param name="isAttribute">
/// Use ATTRIBUTE or ELEMENT for clarity
/// </param>
/// <returns>source or XElement value</returns>
public static XElement Set
(
this XElement source,
string name,
object value,
bool isAttribute,
bool preserveChildren
)
{
source = NameCheck(source, name, out name);
XName xname = ToXName(source, name);
return Set(source, xname, value, isAttribute, preserveChildren);
}
/// <summary>
/// Set any value via its .ToString() method.
/// <para>
/// Returns XElement of source or the new XElement if is an ELEMENT
/// </para>
/// </summary>
/// <param name="isAttribute">
/// Use ATTRIBUTE or ELEMENT for clarity
/// </param>
/// <returns>source or XElement value</returns>
public static XElement Set
(
this XElement source,
XName name,
object value,
bool isAttribute
)
{
return Set(source, name, value, isAttribute, false);
//< false aka don't preserve children of element set.
//< XElement default behavoir.
}
/// <summary>
/// Set any value via its .ToString() method.
/// <para>
/// Returns XElement of source or the new XElement if is an ELEMENT
/// </para>
/// </summary>
/// <param name="isAttribute">
/// Use ATTRIBUTE or ELEMENT for clarity
/// </param>
/// <returns>source or XElement value</returns>
public static XElement Set
(
this XElement source,
XName name,
object value,
bool isAttribute,
bool preserveChildren
)
{
// If value is null or empty, ignore / remove old
bool delete = null == value;
bool modified = false;
string sValue = string.Empty;
if (null != value)
{
sValue = value.ToString();
delete |= string.IsNullOrEmpty(sValue);
}
XElement eValue = null, result = source;
XAttribute aValue = null;
if (null == name)
eValue = source;
else
{
eValue = source.Element(name);
if (name.Namespace == source.Name.Namespace)
aValue = source.Attribute(name.LocalName);
else
aValue = source.Attribute(name);
}
// If changing from Attribute to Element or visa-versa, remove old
if (null != eValue && isAttribute)
{
eValue.Remove();
eValue = null;
modified = true;
}
else if (null != aValue && !isAttribute)
{
aValue.Remove();
aValue = null;
modified = true;
}
// If has an Element tag by the name, replace / remove
if (null != eValue)
{
if (delete)
eValue.Remove();
else
{
// Setting a 'value' to an element, destroys any children
// preserve the child elements!
if (preserveChildren && eValue.HasElements)
{
var children = eValue.Elements().ToArray();
eValue.Value = sValue; // removes any children
foreach (XElement child in children) // re-add child elements
eValue.Add(child);
}
else
eValue.Value = sValue;
result = eValue;
}
modified = true;
}
// else if has an Attribute tag by the name, replace / remove
else if (null != aValue)
{
if (delete)
aValue.Remove();
else
aValue.Value = sValue;
modified = true;
}
// else if value passed wasn't empty, add Attribute or Element
else if (!delete)
{
if (isAttribute)
{
if (name.Namespace == source.Name.Namespace)
source.Add(new XAttribute(name.LocalName, sValue));
else
source.Add(new XAttribute(name, sValue));
}
else
source.Add(result = new XElement(name, sValue));
modified = true;
}
if (modified)
source.SetSave();
return result;
}
#endregion
#region Enumerable
/// <summary>
/// Convert a list of like tags into an enumerable collection.
/// </summary>
public static IEnumerable<T> GetEnumerable<T>
(
this XElement source,
XName name,
Func<XElement, T> convert
)
{
if (null == name)
return GetEnumerable(source, convert);
return GetElements(source, name).Select(x => convert(x));
}
/// <summary>
/// Convert a list of like tags into an enumerable collection.
/// </summary>
public static IEnumerable<T> GetEnumerable<T>
(
this XElement source,
string name,
Func<XElement, T> convert
)
{
if (string.IsNullOrEmpty(name))
return GetEnumerable(source, convert);
source = NameCheck(source, name, out name);
return GetEnumerable(source, ToXName(source, name), convert);
}
/// <summary>
/// Convert a list of like tags into an enumerable collection.
/// </summary>
public static IEnumerable<T> GetEnumerable<T>
(
this XElement source,
Func<XElement, T> convert
)
{
return source.Elements().Select(x => convert(x));
}
/// <summary>
/// Convert an enumerable collection to a list of XElement tags.
/// </summary>
/// <returns>Element that collection was set as children of.</returns>
public static XElement SetEnumerable<T>
(
this XElement source,
string path,
IEnumerable<T> list,
Func<T, XElement> convert
)
{
return SetEnumerable(Path(source, path, true), list, convert);
}
/// <summary>
/// Convert an enumerable collection to a list of XElement tags.
/// </summary>
/// <returns>Element that collection was set as children of.</returns>
public static XElement SetEnumerable<T>
(
this XElement source,
IEnumerable<T> list,
Func<T, XElement> convert
)
{
XElement[] elements = list.Select(t => convert(t)).ToArray();
XElement first = elements.FirstOrDefault() ?? convert(default(T));
source.GetElements(first.Name).Remove();
if (elements.Length > 0)
source.Add(elements);
source.SetSave();
return source;
}
#endregion
#region Utility Methods
/// <summary>
/// If name contains path information to a node, figure it out.
/// </summary>
internal static XElement NameCheck
(
this XElement source,
string name,
out string nameResult
)
{
nameResult = name;
if (!string.IsNullOrEmpty(name))
if (name.Contains('\\') || name.Contains('/'))
{
string[] parts = name.Split('\\', '/');
string path = string.Join("/", parts.Take(parts.Length - 1).ToArray());
source = Path(source, path, true);
nameResult = parts[parts.Length - 1];
}
return source;
}
/// <summary>
/// Navigate to a specific path within source. (create path if it doesn't exist?)
/// </summary>
public static XElement Path(this XElement source, string path, bool create)
{
if (null == path)
throw new ArgumentNullException("Path cannot be null!");
string[] parts = path.Split('\\', '/');
XElement result = source;
foreach (string part in parts)
{
if (create)
result = result.GetElement(part);
else
{
result = result.Element(ToXName(result, part));
if (null == result)
throw new ArgumentOutOfRangeException(part);
}
}
return result;
}
/// <summary>
/// Navigate to a specific path within source. Creates the path if it doesn't exist.
/// </summary>
public static XElement Path(this XElement source, string path)
{
return Path(source, path, true);
}
/// <summary>
/// Return root node of Xml tree of node that calls this
/// </summary>
/// <param name="source"></param>
/// <returns>the root element</returns>
public static XElement Root(this XElement source)
{
XElement root = source;
while (null != root.Parent)
root = root.Parent;
return root;
}
#if !SetSave
/// <summary>
/// Set a save value in the root node so that the containing xml file class
/// knows that the file has changed, and therefore saves the changes.
/// Instead of saving the file everytime even when no changes were made.
/// <remarks>
/// This is an intentionally blank stub so that the file compiles.
/// </remarks>
/// </summary>
public static void SetSave(this XElement source)
{ }
#endif
/// <summary>
/// Convert a name like "im:big" to
/// source.GetNamespaceOfPrefix("im") + "big".
/// </summary>
public static XName ToXName(this XElement source, string name)
{
if (null != source && !string.IsNullOrEmpty(name))
{
XNamespace ns = source.Name.Namespace;
if (name.Contains(':'))
{
string[] parts = name.Split(':');
if (parts.Length > 2)
throw new ArgumentException("Invalid name: " + name);
ns = source.GetNamespaceOfPrefix(parts[0]);
if (null == ns)
throw new ArgumentException(string.Format(
"Undefined namespace abreviation ({0}) for source node. " +
"Provide a source closer to the specified node that contains " +
"the namespace definition.", parts[0]));
name = parts[1];
}
return ns + name;
}
return null;
}
#endregion
#region Demo GetInt
// Demo of creating specific type getter - in this case the Int32 type
public static int GetInt(this XElement source, string name, int defaultValue)
{
// parse path names like: "path/path/element"
source = NameCheck(source, name, out name);
return GetInt(source, ToXName(source, name), defaultValue);
}
public static int GetInt(this XElement source, XName name, int defaultValue)
{
int result;
if (Int32.TryParse(GetString(source, name, null), out result))
return result;
return defaultValue;
}
#endregion
/// <summary>
/// Copy all the elements in A that are not in B to B.
/// </summary>
/// <param name="A"></param>
/// <param name="B"></param>
public static void CopyTo(this XElement A, XElement B)
{
XNode lastB = null, nodeA = null, nodeB = null;
Action Copy_A_To_B = () =>
{
if (null == lastB)
B.AddFirst(nodeA);
else
lastB.AddAfterSelf(nodeA);
};
var listA = A.Nodes().ToList();
var listB = B.Nodes().ToList();
int a, b;
for (a = 0, b = 0; a < listA.Count && b < listB.Count; a++, b++)
{
nodeA = listA[a];
nodeB = listB[b];
XElement xA = nodeA as XElement,
xB = nodeB as XElement;
XText tA = nodeA as XText,
tB = nodeB as XText;
if (null != xA && null != xB)
{
if (xA.Name.LocalName == xB.Name.LocalName)
CopyTo(xA, xB);
else
{
Copy_A_To_B();
CopyTo(A, B); // Restart this iteration for various reasons such as
// the next nodeA might be the same as current nodeB
return;
}
}
else if (null != xA)
Copy_A_To_B();
else if (null != tA && null != tB)
{
if (tA.Value != tB.Value)
tB.Value = tA.Value;
}
else if (null != tA)
Copy_A_To_B();
lastB = nodeB;
}
for (; a < listA.Count; a++)
{
nodeA = listA[a];
Copy_A_To_B();
if (null == lastB)
lastB = B.FirstNode;
else
lastB = lastB.NextNode;
}
}
}
/// <summary>
/// If using something like 'Windows Phone 7' that doesn't have access to
/// the TypeConverter class, then using a TryParse is another option.
/// <para>
/// This class tries to find a TryParse method within the generic type T
/// otherwise it will fail gracefully.
/// </para>
/// </summary>
internal static class ParseCache<T>
{
public static bool TryParse(string sValue, out T value)
{
return func(sValue, out value);
}
delegate bool TryPattern(string sValue, out T value);
private static readonly TryPattern func;
static ParseCache()
{
MethodInfo method = typeof(T).GetMethod(
"TryParse", new Type[] { typeof(string), typeof(T).MakeByRefType() });
if (method == null)
{
if (typeof(T) == typeof(string))
func = delegate(string sValue, out T value)
{ value = (T)(object)sValue; return true; };
else
func = delegate(string sValue, out T value)
{ value = default(T); return false; };
}
else
{
func = (TryPattern)Delegate.CreateDelegate(typeof(TryPattern), method);
}
}
}
/// <summary>
/// Try to get a constructor that takes a string value or the XElement source
/// </summary>
internal static class ConstructorCache<T>
{
public static ConstructorInfo StringInfo { get; private set; }
public static ConstructorInfo XElementInfo { get; private set; }
/// <summary>
/// Try invoking a constructor that takes a single string value or
/// a single XElement value.
/// <remarks>
/// Creating a custom class to parse values either by string or
/// from the XElement source itself, can be a slick way to make this
/// system work for you.
/// </remarks>
/// </summary>
public static bool TryInvoke(XElement source, string value, out T result)
{
result = default(T);
if (null != StringInfo)
{
result = (T)StringInfo.Invoke(new object[] { value });
return true;
}
if (null != XElementInfo)
{
result = (T)XElementInfo.Invoke(new object[] { source });
return true;
}
return false;
}
static ConstructorCache()
{
StringInfo = typeof(T).GetConstructor(new Type[] { typeof(string) });
XElementInfo = typeof(T).GetConstructor(new Type[] { typeof(XElement) });
}
}
}