且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

XPath 1.0查找元素的值是否在值列表中

更新时间:2023-11-27 23:26:28

你可以检查同一个方块内的多个条件括号:

  / Location / Addr [State ='TX'或State ='AL'或State ='MA'] 

或者如果您有一个很长的列表,您可以创建一个状态列表,并使用 contains() function。

  / Location / Addr [contains('TX AL MA ',州)] 

这对两个字母的状态缩写可以正常工作。如果你想使更长的字符串更健壮,你可以在末尾添加一些空格,并检查 _TX _ _AL _ 等(下划线为空格)。

  / Location / Addr [contains('TX AL MA',concat ('',州,'))] 


Is there a way to construct an XPath that evaluates whether an element's value is in a predefined list of values? Something akin to this:

/Location/Addr[State='TX or AL or MA']

Which would match nodes whith State elements for Texas, Alabama, or Massachusetts? I know that I can unpack the expression:

/Location/Addr[State='TX] or  /Location/Addr[State='AL'], etc...

But this is a bit cumbersome since the xpaths are quite long, as is the list of values. My google-fu isn't turning up much on the issue...

You can check multiple conditions inside the same square brackets:

/Location/Addr[State='TX' or State='AL' or State='MA']

Or if you have a really long list, you can create a list of states and use the contains() function.

/Location/Addr[contains('TX AL MA', State)]

This will work fine for two-letter state abbreviations. If you want to make it more robust for longer strings you could add some spaces on the ends and check for _TX_, _AL_, etc. (where the underscores are spaces).

/Location/Addr[contains(' TX AL MA ', concat(' ', State, ' '))]