Home > Net >  XPath match tags with case insentitive
XPath match tags with case insentitive

Time:12-22

I have a feed XML and I want to select items in the file.

<xml>
  <item>
    ...
  </item>
  <item>
    ...
  </item>
  <item>
    ...
  </item>
</xml>

But the user can pass the tag name like <Item> or <ITEM> or something like that. How can I write an XPath to select the items with case insentitive?

CodePudding user response:

There are 2 ways to do this:

  1. Utilizing XPath 2.0 lower-case string function:
//*[lower-case(name())='item']
  1. With matches() XPATH 2.0 function
    One of the matches() function flags is i for case-insensitive matching.
//*[matches(name(),'item','i')]

UPD
I do not know about real case-insensitive matching with XPath 1.0
What you can do is to use or case, like:

//*[name()='item' or name()='Item' or name()='ITEM']

CodePudding user response:

In XPath 1.0 you can use e.g. //*[translate(local-name(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz') = 'item'] but as I said in a comment, consider to preprocess the XML in a transformation step to normalize the case of letters before using normal XPath selectors like //item in the second step.

  • Related