1 16 package org.apache.cocoon.util.jxpath; 17 18 import org.apache.commons.jxpath.AbstractFactory; 19 import org.apache.commons.jxpath.JXPathContext; 20 import org.apache.commons.jxpath.Pointer; 21 import org.w3c.dom.Attr ; 22 import org.w3c.dom.Document ; 23 import org.w3c.dom.Element ; 24 import org.w3c.dom.Node ; 25 26 33 34 public class DOMFactory extends AbstractFactory { 35 36 39 public boolean createObject( 40 JXPathContext context, 41 Pointer pointer, 42 Object parent, 43 String name, 44 int index) 45 { 46 49 addDOMElement((Node ) parent, index, name); 50 51 return true; 52 } 53 54 private void addDOMElement(Node parent, int index, String tag) { 55 int pos = tag.indexOf(':'); 56 String prefix = null; 57 if (pos != -1) { 58 prefix = tag.substring(0, pos); 59 } 60 String uri = null; 61 62 Node child = parent.getFirstChild(); 63 int count = 0; 64 while (child != null) { 65 if (child.getNodeName().equals(tag)) { 66 count++; 67 } 68 child = child.getNextSibling(); 69 } 70 71 Document doc = parent.getOwnerDocument(); 72 73 if (doc != null) { 74 uri = getNamespaceURI((Element )parent, prefix); 75 } else { 76 if (parent instanceof Document ) { 77 doc = (Document )parent; 78 if (prefix != null) { 79 throw new RuntimeException ("Cannot map non-null prefix " + 80 "when creating a document element"); 81 } 82 } else { throw new RuntimeException ("Node of class " + 84 parent.getClass().getName() + " has null owner document " + 85 "but is not a Document"); 86 } 87 88 } 89 90 while (count <= index) { 92 Node newElement = doc.createElementNS(uri, tag); 93 parent.appendChild(newElement); 94 count++; 95 } 96 } 97 98 public String getNamespaceURI(Element element, String prefix) { 99 Node tmp = element; 100 String nsAttr = prefix == null ? "xmlns" : "xmlns:" + prefix; 101 102 while (tmp != null && tmp.getNodeType() == Node.ELEMENT_NODE) { 103 element = (Element )tmp; 104 105 if (prefix == null) { 107 if (element.getPrefix() == null) { 108 return element.getNamespaceURI(); 109 } 110 } else if(prefix.equals(element.getPrefix())) { 111 return element.getNamespaceURI(); 112 } 113 114 Attr nsAttrNode = ((Element )tmp).getAttributeNode(nsAttr); 116 if (nsAttrNode != null) { 117 return nsAttrNode.getValue(); 118 } 119 tmp = tmp.getParentNode(); 120 } 121 return null; 122 } 123 124 public boolean declareVariable(JXPathContext context, String name) { 125 return false; 126 } 127 } 128 | Popular Tags |