0

I have below XML which I need to parse.I need to take name value.But the name element might be case insensitive.How to write a generic Xpath epression to read element with name or Name?

<Employees>
    <Employee id="1">
        <age>29</age>
        <name>Pankaj</name>
        <gender>Male</gender>
        <role>Java Developer</role>
    </Employee>
    <Employee id="2">
        <age>35</age>
        <Name>Lisa</Name>
        <gender>Female</gender>
        <role>CEO</role>
    </Employee>
</Employees>

Below expression will good for name element when we give id as dynamic value.

XPathExpression:

exprs = xpath.compile("/Employees/Employee/@id" + id+ "']/name/text()");
Andersson
  • 51,635
  • 17
  • 77
  • 129
springbootlearner
  • 1,220
  • 4
  • 26
  • 48

2 Answers2

1

Try below XPath to match both name and Name elements

/Employees/Employee/*[matches(name(), "name", "i")]/text()

/*[matches(name(), "name", "i")] should match any element (*) which name (name()) is equal to "name" ignoring ("i") case

Andersson
  • 51,635
  • 17
  • 77
  • 129
1

You can try the XPath translate() function :

translate(string1,string2,string3)

Converts string1 by replacing the characters in string2 with the characters in string3

In your case, the following:

//Employee/*[translate(local-name(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='name']";

will:

  1. For each Employee
  2. Check each children
  3. Convert all letter in the name of the child ( local-name() ) that are Uppercase to lowercase
  4. Compare it to "name"

With this, you don't have to check manually for each possibility and can be re-use for anything else too ; you just have to replace "name" by tho word you want to check.

For futher reading:

translate() --> https://developer.mozilla.org/fr/docs/XPath/Fonctions/translate

local-name() --> https://developer.mozilla.org/fr/docs/XPath/Fonctions/local-name

Andhrím
  • 46
  • 4