/** * Copy NodeList members into this nodelist, adding in * document order. Null references are not added. * * @param iterator NodeIterator which yields the nodes to be added. * @throws RuntimeException thrown if this NodeSet is not of * a mutable type. */ public void addNodes(NodeIterator iterator) { if (!m_mutable) throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESET_NOT_MUTABLE, null)); //"This NodeSet is not mutable!"); if (null != iterator) // defensive to fix a bug that Sanjiva reported. { Node obj; while (null != (obj = iterator.nextNode())) { addElement(obj); } } // checkDups(); }
/** * Create and return a NodeIterator. The NodeIterator is * added to a list of NodeIterators so that it can be * removed to free up the DOM Nodes it references. * * @param root The root of the iterator. * @param whatToShow The whatToShow mask. * @param filter The NodeFilter installed. Null means no filter. * @param entityReferenceExpansion true to expand the contents of * EntityReference nodes * @since WD-DOM-Level-2-19990923 */ public NodeIterator createNodeIterator(Node root, int whatToShow, NodeFilter filter, boolean entityReferenceExpansion) { if (root == null) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_SUPPORTED_ERR", null); throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg); } NodeIterator iterator = new NodeIteratorImpl(this, root, whatToShow, filter, entityReferenceExpansion); if (iterators == null) { iterators = new ArrayList<>(); } iterators.add(iterator); return iterator; }
/** * @serialData Serialized fields. Convert Maps to Hashtables and Lists * to Vectors for backward compatibility. */ private void writeObject(ObjectOutputStream out) throws IOException { // Convert Maps to Hashtables, Lists to Vectors Vector<NodeIterator> it = (iterators == null)? null : new Vector<>(iterators); Vector<Range> r = (ranges == null)? null : new Vector<>(ranges); Hashtable<NodeImpl, Vector<LEntry>> el = null; if (eventListeners != null) { el = new Hashtable<>(); for (Map.Entry<NodeImpl, List<LEntry>> e : eventListeners.entrySet()) { el.put(e.getKey(), new Vector<>(e.getValue())); } } // Write serialized fields ObjectOutputStream.PutField pf = out.putFields(); pf.put("iterators", it); pf.put("ranges", r); pf.put("eventListeners", el); pf.put("mutationEvents", mutationEvents); out.writeFields(); }
@SuppressWarnings("unchecked") private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { // We have to read serialized fields first. ObjectInputStream.GetField gf = in.readFields(); Vector<NodeIterator> it = (Vector<NodeIterator>)gf.get("iterators", null); Vector<Range> r = (Vector<Range>)gf.get("ranges", null); Hashtable<NodeImpl, Vector<LEntry>> el = (Hashtable<NodeImpl, Vector<LEntry>>)gf.get("eventListeners", null); mutationEvents = gf.get("mutationEvents", false); //convert Hashtables back to HashMaps and Vectors to Lists if (it != null) iterators = new ArrayList<>(it); if (r != null) ranges = new ArrayList<>(r); if (el != null) { eventListeners = new HashMap<>(); for (Map.Entry<NodeImpl, Vector<LEntry>> e : el.entrySet()) { eventListeners.put(e.getKey(), new ArrayList<>(e.getValue())); } } }
public static void main(String[] args) throws Exception { Document doc = XmlUtils.loadDoc("/testcode/xpath/data.xml"); String input = args.length != 0 ? args[1] : "guess' or '1'='1"; String query = "//groups/group[@id='" + input + "']/writeAccess/text()"; //selectNodeIterator NodeIterator iterator = XPathAPI.selectNodeIterator(doc, query); XmlUtils.printNodeIterator(iterator); //selectNodeList NodeList nodeList = XPathAPI.selectNodeList(doc, query); XmlUtils.printNodeList(nodeList); //selectSingleNode Node node = XPathAPI.selectSingleNode(doc, query); XmlUtils.printNode(node); //Static string (safe) Node node2 = XPathAPI.selectSingleNode(doc, "//groups/group[@id='guess']/writeAccess/text()".toLowerCase()); XmlUtils.printNode(node2); }
/** * Creates a new node iterator. */ public NodeIterator createNodeIterator(AbstractDocument doc, Node root, int whatToShow, NodeFilter filter, boolean entityReferenceExpansion) throws DOMException { if (root == null) { throw doc.createDOMException (DOMException.NOT_SUPPORTED_ERR, "null.root", null); } NodeIterator result = new DOMNodeIterator(doc, root, whatToShow, filter, entityReferenceExpansion); if (iterators == null) { iterators = new LinkedList(); } iterators.add(result); return result; }
public static DocumentFragment createBlockForSdt(FOConversionContext context, NodeIterator pPrNodeIt, String pStyleVal, NodeIterator childResults, String tag) { DocumentFragment docfrag = createBlock(context, pPrNodeIt, pStyleVal, childResults, true); // Set margins, but only for a shading container, // not a borders container if (tag.equals(Containerization.TAG_SHADING) && docfrag!=null) { // docfrag.getNodeName() is #document-fragment Node foBlock = docfrag.getFirstChild(); if (foBlock!=null) { ((Element)foBlock).setAttribute("margin-top", "0in"); ((Element)foBlock).setAttribute("margin-bottom", "0in"); // ((Element)foBlock).setAttribute("padding-top", "0in"); // ((Element)foBlock).setAttribute("padding-bottom", "0in"); } } return docfrag; }
private boolean evaluate(byte[] data) { try { InputSource inputSource = new InputSource(new ByteArrayInputStream(data)); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder dbuilder = factory.newDocumentBuilder(); Document doc = dbuilder.parse(inputSource); CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); XObject result = cachedXPathAPI.eval(doc, xpath); if (result.bool()) return true; else { NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc, xpath); return (iterator.nextNode() != null); } } catch (Throwable e) { return false; } }
protected void filterPunctuation(MaryData d) { Document doc = d.getDocument(); NodeIterator ni = ((DocumentTraversal) doc).createNodeIterator(doc, NodeFilter.SHOW_ELEMENT, new NameNodeFilter( MaryXML.PARAGRAPH), false); Element p = null; while ((p = (Element) ni.nextNode()) != null) { Node textNode = p.getFirstChild(); String s = textNode.getNodeValue(); System.err.println("FilterPunctuation"); System.err.println(s); s = s.replaceAll("،", ","); //s = s.replaceAll("XX", "YY"); System.err.println(s); textNode.setNodeValue(s); } }
/** * Create and return a NodeIterator. The NodeIterator is * added to a list of NodeIterators so that it can be * removed to free up the DOM Nodes it references. * * @param root The root of the iterator. * @param whatToShow The whatToShow mask. * @param filter The NodeFilter installed. Null means no filter. * @param entityReferenceExpansion true to expand the contents of * EntityReference nodes * @since WD-DOM-Level-2-19990923 */ public NodeIterator createNodeIterator(Node root, int whatToShow, NodeFilter filter, boolean entityReferenceExpansion) { if (root == null) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_SUPPORTED_ERR", null); throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg); } NodeIterator iterator = new NodeIteratorImpl(this, root, whatToShow, filter, entityReferenceExpansion); if (iterators == null) { iterators = new Vector(); } iterators.addElement(iterator); return iterator; }
protected boolean evaluate(InputSource inputSource) { try { DocumentBuilder dbuilder = createDocumentBuilder(); Document doc = dbuilder.parse(inputSource); //An XPath expression could return a true or false value instead of a node. //eval() is a better way to determine the boolean value of the exp. //For compliance with legacy behavior where selecting an empty node returns true, //selectNodeIterator is attempted in case of a failure. CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); XObject result = cachedXPathAPI.eval(doc, xpath); if (result.bool()) return true; else { NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc, xpath); return (iterator.nextNode() != null); } } catch (Throwable e) { return false; } }
/** * Return the concatenation of the values of all text nodes below the given node. One space character is inserted between * adjacent text nodes. * * @param n * n * @return null if n is null */ public static String getPlainTextBelow(Node n) { if (n == null) return null; Document doc = null; if (n.getNodeType() == Node.DOCUMENT_NODE) { doc = (Document) n; } else { doc = n.getOwnerDocument(); } StringBuilder buf = new StringBuilder(); NodeIterator it = ((DocumentTraversal) doc).createNodeIterator(n, NodeFilter.SHOW_TEXT, null, true); Text text = null; while ((text = (Text) it.nextNode()) != null) { buf.append(text.getData().trim()); buf.append(" "); } return buf.toString(); }
public Map<String, Parameter> parseParameters(String response) throws KettleException{ Map<String, Parameter> parameters = new HashMap<String, Parameter>(); try{ DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setNamespaceAware(false); Document doc = dfactory.newDocumentBuilder().parse(new InputSource(new StringReader(response))); Node n; NodeIterator nodeIt = XPathAPI.selectNodeIterator(doc, root_expr); while ((n = nodeIt.nextNode())!= null){ parameters.put(XPathAPI.eval(n, NAME_EXPR).str(), parseParameter(n)); } } catch (Exception e) { throw new KettleException("Error retrieving parameters from WPS response...", e); } return parameters; }
private AbstractFormat buildBoundingBoxFormat(Node n) throws JDOMException, KettleException, DOMException, TransformerException{ List<String> crss = new ArrayList<String>(); String default_crs = XPathAPI.eval(n, DEFAULT_CRS_EXPR).str(); if(default_crs == null) default_crs = EMPTY; Node crs_node; NodeIterator nodeIt = XPathAPI.selectNodeIterator(n, SUPPORTED_CRSS_EXPR); while ((crs_node = nodeIt.nextNode())!= null){ crss.add(crs_node.getNodeValue()); } boolean alreadyExists = false; for(String crs: crss){ if(crs.equals(default_crs)){ alreadyExists = true; break; } } if(!alreadyExists && !default_crs.equals(EMPTY)) crss.add(default_crs); return new BoundingBoxFormat(crss, default_crs); }
private void getComplexFormats(Parameter param, Node n) throws JDOMException, KettleException, DOMException, TransformerException{ Node complex_default = XPathAPI.selectSingleNode(n, DEFAULT_FORMAT_EXPR); AbstractFormat defaultFormat = null; if(complex_default!= null){ defaultFormat = buildComplexFormat(complex_default); param.setDefaultFormat(defaultFormat); } Node complex_supported; NodeIterator nodeIt = XPathAPI.selectNodeIterator(n, SUPPORTED_FORMATS_EXPR); while ((complex_supported = nodeIt.nextNode())!= null){ param.addSupportedFormat(buildComplexFormat(complex_supported)); } if(param.getSupportedFormats().isEmpty() && defaultFormat != null) param.addSupportedFormat(defaultFormat); }
private boolean evaluate(byte[] data) { try { InputSource inputSource = new InputSource(new ByteArrayInputStream(data)); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder dbuilder = factory.newDocumentBuilder(); Document doc = dbuilder.parse(inputSource); CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc,xpath); return iterator.nextNode()!=null; } catch (Throwable e) { return false; } }
private boolean evaluate(String text) { try { InputSource inputSource = new InputSource(new StringReader(text)); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder dbuilder = factory.newDocumentBuilder(); Document doc = dbuilder.parse(inputSource); // We should associated the cachedXPathAPI object with the message being evaluated // since that should speedup subsequent xpath expressions. CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc,xpath); return iterator.nextNode()!=null; } catch (Throwable e) { return false; } }
/** * Outputs information on the matches for debug purposes. * * @param matchSet The set of matching Nodes. * @param doc The first document being differenced */ private static void outputDebug(final NodePairs matchSet, final Document doc) { if (DiffFactory.isDebug()) { NodeIterator ni = ((DocumentTraversal) doc).createNodeIterator( doc.getDocumentElement(), NodeFilter.SHOW_ALL, null, false); Node n; while ((n = ni.nextNode()) != null) { System.err.print(DOMOps.getNodeAsString(n)); if (matchSet.isMatched(n)) { System.err.println(" matches " + DOMOps.getNodeAsString(matchSet.getPartner(n))); } else { System.err.println(" unmatched"); } } ni.detach(); System.err.println(); } }
/** * Returns a list of Nodes sorted according to their depths. * * Does *NOT* include root or documentElement * * TreeSet is sorted in reverse order of depth according to * NodeInfoComparator. * * @param doc The document to be initialised and ordered. * @return A depth-ordered list of the nodes in the doc. */ private static List<NodeDepth> initialiseAndOrderNodes( final Document doc) { NodeIterator ni = ((DocumentTraversal) doc).createNodeIterator( doc, NodeFilter.SHOW_ALL, null, false); List<NodeDepth> depthSorted = new ArrayList<NodeDepth>(); Node n; while ((n = ni.nextNode()) != null) { if (!(NodeOps.checkIfSameNode(doc, n) || NodeOps.checkIfSameNode(doc.getDocumentElement(), n) || n.getNodeType() == Node.DOCUMENT_TYPE_NODE)) { depthSorted.add(new NodeDepth(n)); } } ni.detach(); Collections.sort(depthSorted, new NodeDepthComparator()); return depthSorted; }
public static List<Element> getElementsByTagNameCaseInsensitive(Document doc, final Set<String> lowerCaseNames) { final List<Element> result = Lists.newArrayList(); NodeIterator nodeIterator = ((DocumentTraversal) doc) .createNodeIterator(doc, NodeFilter.SHOW_ELEMENT, new NodeFilter() { public short acceptNode(Node n) { if (lowerCaseNames.contains(n.getNodeName().toLowerCase())) { return NodeFilter.FILTER_ACCEPT; } return NodeFilter.FILTER_REJECT; } }, false); for (Node n = nodeIterator.nextNode(); n != null ; n = nodeIterator.nextNode()) { result.add((Element)n); } return result; }
/** * get the setspec from the item * * @param nativeItem a native item presumably containing a setspec somewhere * @return a String containing the setspec for the item * @exception IllegalArgumentException Something is wrong with the argument. */ public Iterator getSetSpecs(Object nativeItem) throws IllegalArgumentException { ArrayList list = new ArrayList(); Document doc = (Document) nativeItem; try { NodeIterator iter = XPathAPI.selectNodeIterator(doc, "/record/header/setSpec"); Node node = null; while ((node = iter.nextNode()) != null) { list.add(XPathAPI.eval(node, ".").str()); } } catch (TransformerException e) { e.printStackTrace(); return null; } return list.iterator(); // return (Iterator)((HashMap)nativeItem).get("setSpecs"); }
protected boolean evaluate(InputSource inputSource) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder dbuilder = factory.newDocumentBuilder(); Document doc = dbuilder.parse(inputSource); //An XPath expression could return a true or false value instead of a node. //eval() is a better way to determine the boolean value of the exp. //For compliance with legacy behavior where selecting an empty node returns true, //selectNodeIterator is attempted in case of a failure. CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); XObject result = cachedXPathAPI.eval(doc, xpath); if (result.bool()) return true; else { NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc, xpath); return (iterator.nextNode() != null); } } catch (Throwable e) { return false; } }
public NodeIterator selectNodeIterator(Node contextNode, String xpath) throws TransformerException { switch (xpathEngine) { case Xalan: checkContextNode(contextNode); return xpathApi.selectNodeIterator(contextNode, xpath); default: return new JXPathNodeIterator(selectList(contextNode, xpath)); } }