4 /// <summary>
5 /// Gets the case-sensitive LocalName of a child element.
6 /// </summary>
7 /// <param name="parentElement">XElement object to search through</param>
8 /// <param name="name">The (case insensitive) LocalName of the child element you are looking for</param>
9 /// <returns>String containing the LocalName of the XName child elements</returns>
10 public static class MyCustomExtensions
11 {
12 public static string GetChildElementName(this XElement parentElement, string name)
13 {
16 var children = from c in parentElement.Elements()
17 where c.Name.LocalName.ToLower() == name.ToLower()
18 select c.Name;
19 if (children.Count() > 0)
20 { return children.First().LocalName; }
21 else
22 { return String.Empty; }
23 }
24 }
Now to use the extension method, I can just use the GetChildElementName method like it was always a part of the XElement class as long as I have a reference to the namespace that the MyCustomExtensions class is inside of. I’ll have intellisense available for me and everything.
15 File Defined somewhere as test.xml
16 <Test>
17 <Path>http://www.google.com</Path>
18 <Path>http://www.bing.com</Path>
19 <Path>http://www.yahoo.com</Path>
20 </Test>
21 */
22 XElement myTestElement = XElement.Load("test.xml");
23
24 // Use GetChildElementName() to get the name of "Path" in case I can’t trust what case was used
25 string name = myTestElement.GetChildElementName("path");
26 IEnumerable<XElement> children = myTestElement.Elements(name);