按轴表达式拆分xpath字符串

时间:2013-06-03 16:10:29

标签: java string xpath

我有这样的XPath:

something1/something2/AXES::tag/something3...

其中AXES是一组有限的单词:

  • 属性
  • ...

所以我必须将这个xpath分成三部分:

  1. something1 / somthing2 /
  2. AXES ::标签
  3. something3 ...
  4. 我该怎么做? 我意识到这很简单,但它应该尽可能快地工作。


    我的解决方案(当然它不是最佳的):

    private static String[] splitForFirstAxes(String s){
        String[] a = new String[3];
        int i = s.indexOf("::",0);
        if (0 > i ) return null;
        String part1 = s.substring(0, i);
        String part2 = s.substring(i+2);
        int part1LastsSlash = part1.lastIndexOf('/');
        int part2FirstSlash = part2.indexOf('/');
        a[0] = part1.substring(0, part1LastsSlash);// First part
        a[2] = part2.substring(part2FirstSlash+1);// Second part
        a[1] = part1.substring(part1LastsSlash+1) +"::" +part2.substring(0,part2FirstSlash);// Axes
        return a;
    }
    

2 个答案:

答案 0 :(得分:0)

String xpath = "something1/something2/AXES::tag/something3";
String[] parts = xpath.split("/");

按索引访问每个部分:

System.out.println(parts[0] + parts[1]);
System.out.println(parts[2]);
System.out.println(parts[3]);

结果:

something1something2
AXES::tag
something3

答案 1 :(得分:0)

这正是您所寻找的:

String input = "something1/something2/AXES::tag/something3...";
String[] tokens = input.split("/");
List<String> resultList = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (String token : tokens) {
    if (token.contains("::")) {
        if (sb.length() > 0) {
            resultList.add(sb.append("/").toString());
        }
        resultList.add(token);
        sb = new StringBuilder();
    } else {
        if (sb.length() > 0) {
            sb.append("/");
        }
        sb.append(token);
    }
} 
if (sb.length() > 0) {
    resultList.add(sb.toString());
}
System.out.println(resultList);

输出:

[something1/something2/, AXES::tag, something3...]