Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XML

Case Insensitive XPath Queries

5.00/5 (2 votes)
3 Apr 2018CPOL 15.8K  
How to perform XPath queries on all lower case elements

Introduction

Finding values in an XML file can be done quickly with the use of XPath queries. The other day, we were writing our queries but found the need to find elements in the XML without being bothered with case sensitivity. Yeah, I know, you're right, but programming can be dirty sometimes.

Using the Code

The following extension methods enabled us to execute XPath-queries case-insensitive.

C#
public static class XDocumentExtensions
{
	/// Transform the elements in the XDocument to all lower case
	/// Only the elements are affected, not the attributes
	public static XDocument TransformToLowerCaseElements(this XDocument value)
	{
		value.DescendantNodes().OfType<XElement>().ToList()
		  .ForEach(n => n.Name = n.Name.ToString().ToLower());
		return value;
	}

	/// Transforms the XDocument to elements with lower case and returns the query result
	public static XElement XPathSelectElementIgnoreCase(this XDocument value, string xpath)
	{
		return value.TransformToLowerCaseElements().XPathSelectElement(xpath);
	}

	/// Transforms the XDocument to elements with lower case and returns the query result
	public static IEnumerable<XElement> XPathSelectElementsIgnoreCase
	                                            (this XDocument value, string xpath)
	{
		return value.TransformToLowerCaseElements().XPathSelectElements(xpath);
	}
}

Sample Usage

Take the following XML as an example:

XML
var xmlstring=@"<?xml version=""1.0"" encoding=""utf-8""?>
<Parents>
	<Parent Name=""Chris"" Type=""father"">
		<Child>
			<Name>Jonathan</Name>
			<AGE>13</AGE>
		</Child>
	</Parent>
</Parents>";

If we load this into an XDocument and then transform it into lower case:

C#
var xdoc = XDocument.Parse(xmlstring);
xdoc.TransformToLowerCaseElements();

The XML will look like:

XML
<?xml version="1.0" encoding="utf-8"?>
<parents>
	<parent Name="Chris" Type="father">
		<child>
			<name>Jonathan</name>
			<age>13</age>
		</child>
	</parent>
</parents>

Now, knowing that all elements can be made lowercase in this XML, we are able to query it with our new extension method:

C#
var xdoc = XDocument.Parse(xmlstring);
var age = xdoc.XPathSelectElementIgnoreCase("parents/parent/child/age").Value;

Points of Interest

At first, I also had the xpath parameter in the XPathSelectElementIgnoreCase transformed to lower case. I removed that because it made it impossible to use the attributes in the queries I was constructing.

These extension methods helped us a lot while writing our code and tests whilst the xsd wasn't yet definitive.

To find out more about case insensitivity in XPath queries, have a look at:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)