3

I would like to search node via Xpath case insensitve.

<Validation>
    <Presentation>
        <Slide Tag= "Test">
            <FontSize Value = "36"/>
        </Slide>
    </Presentation>
</Validation>

I've used this code

String xPath = string.Format("/Validation/Presentation/Slide[lower-case(@Tag)='{0}'][1]", "test");
XmlNode node = doc.DocumentElement.SelectSingleNode(xPath);

but it throws an XPath Exceptions: Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function. Where did I go wrong?

3
  • When you used XPath :). But seriously, is there a reason not to use XDocument here? Commented May 29, 2015 at 13:03
  • Your answer is here Getting attribute using XPath stackoverflow.com/questions/4531995/… Commented May 29, 2015 at 13:16
  • @bilal yes, but i need also case insensitive.. Commented May 29, 2015 at 13:37

3 Answers 3

10

.NET doesn't support XPath 2.0.

So you can use this abomination:

    /Validation/Presentation/Slide[translate(@Tag,
   'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 
   'abcdefghijklmnopqrstuvwxyz')= 'test']

(I hard coded your value in for ease of testing with XPathBuilder.)

Sign up to request clarification or add additional context in comments.

Comments

6

Have you tried this?
INFO: Use XPath to Perform a Case-Insensitive Search with MSXML: https://support.microsoft.com/en-us/kb/315719

use translate

doc.DocumentElement.selectSingleNode("/Validation/Presentation/Slide[translate(@Tag, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') = 'test']")

Comments

5

lower-case is XPath 2.0 function and .NET itself supports only Xpath 1.0 expressions, so you can't use it this way.

Alternatively you can use Linq2Xml:

var doc = XDocument.Load(@"your_file_Name");
var node = doc.XPathSelectElements("/Validation/Presentation/Slide")
               .FirstOrDefault(x => x.Attribute("Tag") != null 
                                    && String.Equals(x.Attribute("Tag").Value, "test",
                                                 StringComparison.CurrentCultureIgnoreCase));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.