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开发者_如何学JAVA#/.Net 3.5.
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>
Before you load the XML string make lower-case. That will solve the issue. I use this method myself.
精彩评论