01: /*
02: * This file is part of PFIXCORE.
03: *
04: * PFIXCORE is free software; you can redistribute it and/or modify
05: * it under the terms of the GNU Lesser General Public License as published by
06: * the Free Software Foundation; either version 2 of the License, or
07: * (at your option) any later version.
08: *
09: * PFIXCORE is distributed in the hope that it will be useful,
10: * but WITHOUT ANY WARRANTY; without even the implied warranty of
11: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12: * GNU Lesser General Public License for more details.
13: *
14: * You should have received a copy of the GNU Lesser General Public License
15: * along with PFIXCORE; if not, write to the Free Software
16: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17: *
18: */
19: package de.schlund.pfixcore.oxm.impl;
20:
21: import org.w3c.dom.Element;
22: import org.w3c.dom.Node;
23:
24: /**
25: *
26: * @author mleidig@schlund.de
27: *
28: */
29: public class DOMXPathPosition implements XPathPosition {
30:
31: private Node node;
32:
33: public DOMXPathPosition(Node node) {
34: this .node = node;
35: }
36:
37: public String getXPath() {
38: StringBuilder sb = new StringBuilder();
39: buildXPath(node, sb);
40: return sb.toString();
41: }
42:
43: private void buildXPath(Node node, StringBuilder builder) {
44: if (node != null) {
45: if (node.getNodeType() == Node.ELEMENT_NODE) {
46: Element elem = (Element) node;
47: Node parentNode = elem.getParentNode();
48: if (parentNode != null
49: && parentNode.getNodeType() == Node.ELEMENT_NODE) {
50: int pos = 1;
51: Node prevNode = elem.getPreviousSibling();
52: while (prevNode != null) {
53: if (prevNode.getNodeType() == Node.ELEMENT_NODE) {
54: if (prevNode.getNodeName().equals(
55: elem.getNodeName()))
56: pos++;
57: }
58: prevNode = prevNode.getPreviousSibling();
59: }
60: builder.insert(0, "/" + elem.getNodeName() + "["
61: + pos + "]");
62: buildXPath(parentNode, builder);
63: } else {
64: builder.insert(0, "/" + elem.getNodeName());
65: }
66: } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
67: builder.insert(0, "/@" + node.getNodeName());
68: buildXPath(node.getParentNode(), builder);
69: }
70: }
71: }
72:
73: }
|