如何获取XML文件文本中单词的排名?求解Vdepth排名提取失败问题
Hey there! Let's break down why your current XPath isn't working and how to get that rank value you need.
The Core Problem
Your XML's mnemonicList contains a single text node with the comma-separated string: Mdepth,Vdepth,Bit Dist,TQ on btm. When you use //logData/mnemonicList/text(), you're grabbing that one entire string—not four separate nodes. That's why (//logData/mnemonicList/text())[2] throws "NO MATCH!"—there's no second text node to select.
Solutions Based on Your XPath Version
If You're Using XPath 2.0+ (Most Modern Tools Support This)
This is the cleanest approach. Use the tokenize() function to split the string into a sequence of values, then either grab the second element directly or get its index (your desired rank value):
- To get the "Vdepth" string itself:
tokenize(//logData/mnemonicList/text(), ',')[2] - To get its rank (the number 2):
index-of(tokenize(//logData/mnemonicList/text(), ','), 'Vdepth')
The index-of() function will return the position of "Vdepth" in the split list, which is exactly the rank you need.
If You're Stuck With XPath 1.0 (No Built-in Split Function)
We have to get creative with string manipulation. To calculate the rank of "Vdepth", count how many commas appear before it, then add 1:
string-length(substring-before(//logData/mnemonicList/text(), 'Vdepth')) - string-length(translate(substring-before(//logData/mnemonicList/text(), 'Vdepth'), ',', '')) + 1
Here's how this works:
substring-before(..., 'Vdepth')grabs everything before "Vdepth" (Mdepth,)translate(..., ',', '')removes all commas from that substring, leavingMdepth- Subtract the length of the comma-free string from the original substring length to get the number of commas (1)
- Add 1 to get the rank (2)
Quick Verification
If you just want to confirm "Vdepth" is in the second position, you can use this check:
starts-with(substring-after(//logData/mnemonicList/text(), ','), 'Vdepth')
It will return true if "Vdepth" follows the first comma.
内容的提问来源于stack exchange,提问作者Jun

