Sri Reddy
Sri Reddy

Reputation: 7012

Can XPathSelectElement ignore case?

Is there a way to ignore case when we try to use XPathSelectElement or any operation like to retrieving attributes from XDocument? The purpose for asking this question is that, I have some configuration files (xml) and I am writing a generic code that will read the config files to get required information for XPathSelectElement. Also, I try to get the values of attributes. Even if someone puts the nodes/attributes in different case, my program should be able to work without fail.

I use C#/.Net 3.5.

Upvotes: 1

Views: 2645

Answers (2)

user3514987
user3514987

Reputation: 220

Before you load the XML string make lower-case. That will solve the issue. I use this method myself.

Upvotes: 0

Tomalak
Tomalak

Reputation: 338336

You can't ignore case with XPath. You can accomodate, though.

For example - elements, assuming they contain letters in the ASCII range only:

//*[
  translate(
    name(), 
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 
    'abcdefghijklmnopqrstuvwxyz'
  ) = 'myname'
]

Attributes would work the same (with @* in place of *).

If you do not want to bloat your XPath expressions with this, you could lower-case all element- and attribute names beforehand, for example via XSLT:

<xsl:stylesheet version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
  <xsl:variable name="upper" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />
  <xsl:variable name="lower" select="'abcdefghijklmnopqrstuvwxyz'" />

  <xsl:template match="node()">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="*">
    <xsl:element name="{translate(name(), $upper, $lower)}">
      <xsl:apply-templates select="node() | @*" />
    </xsl:element>
  </xsl:template>

  <xsl:template match="@*">
    <xsl:attribute name="{translate(name(), $upper, $lower)}">
      <xsl:value-of select="." />
    </xsl:attribute>
  </xsl:template>
</xsl:stylesheet>

Upvotes: 1

Related Questions