Java tutorial
//package com.java2s; /******************************************************************************* * Copyright (c) 2012 Firestar Software, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Firestar Software, Inc. - initial API and implementation * * Author: * Gabriel Oancea * *******************************************************************************/ import javax.xml.namespace.NamespaceContext; public class Main { public static final String DEFAULT_NS = "DEFAULT_NS"; private static String getValidXpath(String xPath, NamespaceContext context) { if (context == null) return xPath; String namespaceURI = context.getNamespaceURI(DEFAULT_NS); // check if there is any default namespace if (namespaceURI != null && !namespaceURI.isEmpty()) { StringBuilder stringBuilder = new StringBuilder(); String[] tags = xPath.split("/"); int length = tags.length; for (int i = 0; i < length - 1; i++) { createNodeXPath(stringBuilder, tags[i]); stringBuilder.append("/"); } createNodeXPath(stringBuilder, tags[length - 1]); return stringBuilder.toString(); } return xPath; } private static void createNodeXPath(StringBuilder stringBuilder, String tag) { int icln = indexOfNotInQuotes(tag, ':'); int icat = indexOfNotInQuotes(tag, '@'); if (icln < 0 && icat != 0) { stringBuilder.append(DEFAULT_NS); stringBuilder.append(":"); } // todo rewrite, only for test tag = tag.replace("[templateId", "[" + DEFAULT_NS + ":" + "templateId"); stringBuilder.append(tag); } private static int indexOfNotInQuotes(String s, char x) { int i = s.indexOf(x); if (i < 0) return i; i = -1; int j = 0; boolean insideQuotes = false; while (j < s.length() && i < 0) { char c = s.charAt(j); if (c == '\'') { if (insideQuotes) { if (0 <= j - 1 && s.charAt(j - 1) != '\\') insideQuotes = false; } else insideQuotes = true; } if (c == x && !insideQuotes) i = j; j++; } return i; } private static int indexOfNotInQuotes(String s, String x) { int i = s.indexOf(x); if (i < 0) return i; i = -1; int j = 0; int n = x.length(); boolean insideQuotes = false; while (j + n < s.length() && i < 0) { char c = s.charAt(j); if (c == '\'') { if (insideQuotes) { if (0 <= j - 1 && s.charAt(j - 1) != '\\') insideQuotes = false; } else insideQuotes = true; } if (!insideQuotes && x.equals(s.substring(j, j + n))) i = j; j++; } return i; } }