Here you can find the source of getXPathToContent(final Node root, final String selectedContent)
Parameter | Description |
---|---|
root | The root element of the XML document |
selectedContent | The selected character data |
private static String getXPathToContent(final Node root, final String selectedContent)
//package com.java2s; /******************************************************************************* * Copyright (c) 2009 Dominik Schadow - http://www.xml-sicherheit.de 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: Dominik Schadow - initial API and implementation *******************************************************************************/ import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** Contains the XPath to the selected element content. */ private static String xpathExpressionToContent = null; /**/*from w ww . jav a2 s . c om*/ * Determines the XPath expression to the selected character data (element content). The first * matching content is used, so this XPath may point to another element content. * * @param root The root element of the XML document * @param selectedContent The selected character data * @return The XPath expression to the selected character data */ private static String getXPathToContent(final Node root, final String selectedContent) { NodeList childList = root.getChildNodes(); Node childNode = null; for (int i = 0, length = childList.getLength(); i < length && xpathExpressionToContent == null; i++) { childNode = childList.item(i); if (childNode.getNodeType() == Node.TEXT_NODE) { if (childNode.getTextContent().equals(selectedContent)) { xpathExpressionToContent = getXPathExpression(childNode.getParentNode()); } } getXPathToContent(childNode, selectedContent); } return xpathExpressionToContent + "/text()"; //$NON-NLS-1$ } /** * Returns the unique XPath expression for the given node. * * @param node The node to determine the XPath for * @return The XPath expression as string */ private static String getXPathExpression(final Node node) { String xpathExpression = node.getNodeName(); if (node.getParentNode() != null) { int index = 0; Node prec = node; while (prec != null) { if (prec.getNodeName().equals(node.getNodeName())) { index++; } prec = prec.getPreviousSibling(); } if (node.getParentNode() instanceof Document) { ; // do nothing } else { xpathExpression = getXPathExpression(node.getParentNode()) + "/" + xpathExpression //$NON-NLS-1$ + "[" + String.valueOf(index) + "]"; //$NON-NLS-1$ //$NON-NLS-2$ } } return xpathExpression; } }