1 package org.xmldb.xupdate.lexus.commands; 2 3 55 56 import org.w3c.dom.Attr ; 57 import org.w3c.dom.Element ; 58 import org.w3c.dom.Node ; 59 import org.w3c.dom.NodeList ; 60 import org.xmldb.common.xml.queries.XObject; 61 import org.xmldb.common.xml.queries.XPathQuery; 62 import org.xmldb.common.xml.queries.XPathQueryFactory; 63 64 69 public class InsertVariable extends InsertStates { 70 71 74 public InsertVariable() { 75 super(); 76 } 77 78 79 82 public Node execute(Node contextNode) throws Exception { 83 String selection = (String ) attributes.get("select"); 84 85 NodeList newNodes = null; 86 if (selection.charAt(0) == '$') { 87 String name = selection.substring(1); 88 newNodes = CommandConstants.tempTree.getTreeForName(name); 89 } else { 90 newNodes = selectNewNodes(selection, contextNode); 91 } 92 93 Node result = contextNode; 94 int newNodesLength = newNodes.getLength(); 95 for (int i = 0; i < newNodesLength; i++) { 96 Node current = newNodes.item(i); 97 switch (current.getNodeType()) { 98 case Node.ATTRIBUTE_NODE: 99 switch (contextNode.getNodeType()) { 100 case Node.ELEMENT_NODE: 101 Attr attribute = (Attr ) current.cloneNode(true); 102 ((Element ) contextNode).setAttributeNode(attribute); 103 result = attribute; 104 break; 105 default: 106 throw new Exception ("can't append attribute !"); 107 } 108 break; 109 default: 110 result = contextNode.appendChild(current.cloneNode(true)); 111 } 112 } 113 return result; 114 } 115 116 119 protected NodeList selectNewNodes(String query, Node contextNode) throws Exception { 120 XPathQuery xpath = XPathQueryFactory.newInstance().newXPathQuery(); 121 xpath.setQString(query); 122 XObject xResult = xpath.execute(contextNode); 123 if (xResult.getType() != XObject.CLASS_NODESET) { 124 throw new Exception ("XPath leads not to a Node or NodeList !"); 125 } 126 NodeList result = xResult.nodeset(); 127 return result; 128 } 129 } 130 131 | Popular Tags |