Home Contact

X

Coder, not artist.

News

All code on here is free, but as a consequence it's up to you to check it, ha! If you have any questions, please use the contact button!

Twitter












Archives

Post Categories

Image Galleries

Syndication:

XElement case insensitive 'Element' extension

Just a small bit of code, I've been playing around with converting some Xml* code to Linq to Xml code, and pretty successfully achieved everything I wanted, one thing missing was the ability to retrieve an XElement ignoring case.

First - I'd like mention that yes I know Xml is case sensitive - and this is a bad thing to do - but I needed to do it due to some wierdness in the input xml...

Anyhews, below is the extension method I wrote to deal with this..

public static class XElementExtensions
{
    /// <summary>Gets the first (in document order) child element with the specified <see cref="XName"/>.</summary>
    /// <param name="element">The element.</param>
    /// <param name="name">The <see cref="XName"/> to match.</param>
    /// <param name="ignoreCase">If set to <c>true</c> case will be ignored whilst searching for the <see cref="XElement"/>.</param>
    /// <returns>A <see cref="XElement"/> that matches the specified <see cref="XName"/>, or null. </returns>
    public static XElement Element( this XElement element, XName name, bool ignoreCase )
    {
        var el = element.Element( name );
        if (el != null)
            return el;
 
        if (!ignoreCase)
            return null;
 
        var elements = element.Elements().Where( e => e.Name.LocalName.ToString().ToLowerInvariant() == name.ToString().ToLowerInvariant() );
        return elements.Count() == 0 ? null : elements.First();
    }
}

 

Cheers!

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Thursday, December 03, 2009 3:50 AM

Feedback

# re: XElement case insensitive 'Element' extension

I used something like this b/c documentation was distributed with errors.

FYI, there appears to be a bug in the posted code...

The where needs to be:

.Where(e => e.Name.LocalName.ToString().ToLowerInvariant() == name.LocalName.ToString().ToLowerInvariant());

name.LocalName.ToString().ToLowerInvariant() instead of just name.ToString().ToLowerInvariant() 1/30/2011 6:04 AM | CoderX

# re: XElement case insensitive 'Element' extension

There is a way to do the same, but more performant:

return element.SingleOrDefault(s => string.Compare(s.Name.ToString(), name, true) == 0);

Just one line. No matter if name exists, this will return null or XElement found. 4/28/2011 1:37 AM | Adrian

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: