List of usage examples for org.dom4j XPath selectNodes
List<Node> selectNodes(Object context);
selectNodes
performs this XPath expression on the given Node or List of Node s instances appending all the results together into a single list. From source file:cz.mzk.editor.server.newObject.MonographBuilder.java
License:Open Source License
@SuppressWarnings("unchecked") private void updateLanguages(Document doc, XPath xpath) { List<? extends Node> nodes = xpath.selectNodes(doc); for (Node languageNode : nodes) { Element languageEl = (Element) languageNode; String originalLang = languageEl.getTextTrim(); languageEl.clearContent();/*w w w. j ava 2 s . c o m*/ languageEl.addText(transformLanguage(originalLang)); } }
From source file:de.innovationgate.wga.server.api.Xml.java
License:Open Source License
/** * Executes an XPath expression on some XML text or JavaBean * This function always returns lists. If the xpath expression matches only a single values it will return it as single element in a list. If you only want to retrieve single values use xpath(). * The given object to parse as XML is either a dom4j branch object (mostly document or element), a String containing XML text or a JavaBean. In the last case this function uses JXPath functionality to find a bean property value. * This uses the Apache library JXPath under the hood. See their documentation for details how XPath is used to browser JavaBeans. * @param object Object to inspect/* w w w . j av a 2 s. c o m*/ * @param xpath XPath expression * @param ns Map of namespace prefix declarations used in the XPath. Keys are prefixes, values are namespace URIs. * @return Returned value * @throws DocumentException */ @SuppressWarnings("unchecked") public Object xpathList(Object object, String xpath, Map<String, String> ns) throws WGException, DocumentException { List<Object> results; if (object instanceof String || object instanceof Branch) { Branch branch = retrieveBranch(object); XPath xpathObj = createXPath(xpath, branch, ns); results = xpathObj.selectNodes(branch); } // Do JXPath on Bean else { JXPathContext jxContext = JXPathContext.newContext(object); jxContext.setLenient(true); results = jxContext.selectNodes(xpath); } return convertXMLObjects(results, true); }
From source file:de.tudarmstadt.ukp.dkpro.wsd.io.reader.MASCReader.java
License:Apache License
@SuppressWarnings("unchecked") private String processNode(JCas jCas, Element node, Element root) { String sentence = null;/*from www . j a va 2 s . co m*/ String id = node.valueOf("@" + ATTR_ID); Element link = node.element(ELEMENT_LINK); String targets = link.valueOf("@targets"); // the ID of the region // element this node points // to String[] tokens = targetItems2sentences.get(targets).split("<sep>"); int begin = Integer.parseInt(tokens[1]); int end = Integer.parseInt(tokens[2]); // get the annotation element "a" which points to the node which is // being processed XPath pathToA = createXPath("//masc:" + ELEMENT_A + "[@ref='" + id + "']"); List<Node> as = pathToA.selectNodes(root); Node a = as.get(0); // Get all senses specified for the item // XPath does not work, even when one specifies the absolute path to the // element containing the sense; // only when the root is changed, global search "//" works; weird! document.setRootElement((Element) a); XPath pathToSenses = createXPath("//masc:" + ELEMENT_F + "[@name='sense']"); List<Node> senseNodes = pathToSenses.selectNodes(a); HashSet<String> senses = resolveIAA(senseNodes, lemma + "-" + pos + "_" + id); // if the sense annotation is OK, create WSDItem and WSDResult if (senses != null) { LexicalItemConstituent c = createLexicalItemConstituent(jCas, lemma + "_" + id, LIC_TYPE_HEAD, begin, end); WSDItem w = createWsdItem(jCas, lemma + "_" + id, begin, end, pos, lemma); w.setConstituents(new FSArray(jCas, 1)); w.setConstituents(0, c); FSArray senseArray = new FSArray(jCas, senses.size()); List<String> sensesList = new ArrayList<String>(senses); for (int i = 0; i < sensesList.size(); i++) { String nextSense = sensesList.get(i); if (nextSense.contains(" ") || nextSense.length() == 1) { document.setRootElement(root); // set back the XML root to // the original root node return null; } Sense sense = new Sense(jCas); sense.setId(nextSense); sense.setConfidence(1.0); sense.addToIndexes(); senseArray.set(i, sense); } WSDResult wsdResult = new WSDResult(jCas); wsdResult.setWsdItem(w); wsdResult.setSenses(senseArray); wsdResult.setSenseInventory(senseInventory); wsdResult.setDisambiguationMethod(DISAMBIGUATION_METHOD_NAME); wsdResult.addToIndexes(); sentence = tokens[0]; // set the context of the target item to the // sentence in which this item occurs } document.setRootElement(root); // set back the XML root to the original // root node return sentence; }
From source file:dk.netarkivet.common.utils.SimpleXml.java
License:Open Source License
/** * Get the first entry that matches the key. Keys are constructed as a dot separated path of xml tag names. Example: * The following XML definition of a user name <dk><netarkivet><user>ssc</user> * </netarkivet></dk> is accessed using the path: "dk.netarkivet.user" * * @param key the key of the entry./* w w w . j a va2s. co m*/ * @return the first entry that matches the key. * @throws UnknownID if no element matches the key * @throws ArgumentNotValid if the key is null or empty */ public String getString(String key) { ArgumentNotValid.checkNotNullOrEmpty(key, "key"); XPath xpath = getXPath(key); List<Node> nodes = xpath.selectNodes(xmlDoc); if (nodes == null || nodes.size() == 0) { throw new UnknownID("No elements exists for the path '" + key + "' in '" + source + "'"); } Node first = nodes.get(0); return first.getStringValue().trim(); }
From source file:dk.netarkivet.common.utils.SimpleXml.java
License:Open Source License
/** * Return a tree structure reflecting the XML and trimmed values. * * @param path Dotted path into the xml. * @return A tree reflecting the xml at the given path. * @throws UnknownID If the path does not exist in the tree or is ambiguous */// w w w . j a va2 s .c om public StringTree<String> getTree(String path) { ArgumentNotValid.checkNotNullOrEmpty(path, "String path"); XPath xpath = getXPath(path); List<Node> nodes = xpath.selectNodes(xmlDoc); if (nodes == null || nodes.size() == 0) { throw new UnknownID("No path '" + path + "' in XML document '" + source + "'"); } else if (nodes.size() > 1) { throw new UnknownID("More than one candidate for path '" + path + "' in XML document '" + source + "'"); } return XmlTree.getStringTree(nodes.get(0)); }
From source file:eu.planets_project.pp.plato.util.XMLCompare.java
License:Open Source License
private void excludeNodes(Document doc) { Element root = doc.getRootElement(); for (String xpathString : excludedNodes) { XPath xpath = doc.createXPath(xpathString); List<Node> l = xpath.selectNodes(root); for (Node n : l) { n.detach();/*from w w w. j a v a 2s.c o m*/ } } }
From source file:eu.scape_project.planning.xml.ProjectExportAction.java
License:Apache License
/** * Returns a list of object IDs that are stored in the document without * binary data./* w ww .j ava2 s . c o m*/ * * @param doc * the document to search * @return a list of IDs */ private List<Integer> getBinaryObjectIds(Document doc) { // Get data elements that have data and a number as content XPath xpath = doc.createXPath("//plato:data[@hasData='true' and number(.) = number(.)]"); Map<String, String> namespaceMap = new HashMap<String, String>(); namespaceMap.put("plato", PlanXMLConstants.PLATO_NS); xpath.setNamespaceURIs(namespaceMap); @SuppressWarnings("unchecked") List<Element> elements = xpath.selectNodes(doc); List<Integer> objectIds = new ArrayList<Integer>(elements.size()); for (Element element : elements) { objectIds.add(Integer.parseInt(element.getStringValue())); } return objectIds; }
From source file:eu.scape_project.planning.xml.ProjectExportAction.java
License:Apache License
/** * Returns the collection profile IDs that are in the document without data. * //from w ww .j a va2s . c om * @param doc * the docuemnt to seasrch * @return a list of IDs */ private List<Integer> getPreservationActionPlanIds(Document doc) { // Get data elements that have data and a number as content XPath xpath = doc.createXPath("//plato:preservationActionPlan[number(.) = number(.)]"); Map<String, String> namespaceMap = new HashMap<String, String>(); namespaceMap.put("plato", PlanXMLConstants.PLATO_NS); xpath.setNamespaceURIs(namespaceMap); @SuppressWarnings("unchecked") List<Element> elements = xpath.selectNodes(doc); List<Integer> objectIds = new ArrayList<Integer>(elements.size()); for (Element element : elements) { objectIds.add(Integer.parseInt(element.getStringValue())); } return objectIds; }
From source file:fr.itris.glips.svgeditor.display.canvas.SVGCanvas.java
License:LGPL
/** * add style.svg to doc//from w ww . ja v a 2 s . co m * @param doc * @return */ public Document addStyle(Document doc) { //converts the svg document into xml strings StringBuffer buffer = new StringBuffer(""); org.dom4j.Document doc4j = null; for (Node node = doc.getFirstChild(); node != null; node = node.getNextSibling()) { XMLPrinter.writeNode(node, buffer, 0, true, null); } try { doc4j = new SAXReader().read(new ByteArrayInputStream(buffer.toString().getBytes("utf8"))); if (doc4j != null) { XPath x = doc4j.createXPath("/uri:svg/uri:defs"); x.setNamespaceURIs(getNamespace(doc4j)); List<org.dom4j.Element> list = x.selectNodes(doc4j); for (org.dom4j.Element t : list) { if ("defs".equalsIgnoreCase(t.getName())) { org.dom4j.Element style = t.addElement("style"); style.addAttribute("type", "css/text"); style.addText(Editor.getEditor().getSymbolManager().getStyle()); } } } } catch (Exception e) { e.printStackTrace(); } String result = SymbolManager.XML2Str(doc4j); // System.out.println(result.substring(result.indexOf("<svg"))); return SymbolManager.Str2XML(result.substring(result.indexOf("<svg"))); }
From source file:hudson.model.Api.java
License:Open Source License
/** * Exposes the bean as XML./*from w w w . j av a 2 s . c om*/ */ public void doXml(StaplerRequest req, StaplerResponse rsp, @QueryParameter String xpath, @QueryParameter String wrapper, @QueryParameter String tree, @QueryParameter int depth) throws IOException, ServletException { setHeaders(rsp); String[] excludes = req.getParameterValues("exclude"); if (xpath == null && excludes == null) { // serve the whole thing rsp.serveExposedBean(req, bean, Flavor.XML); return; } StringWriter sw = new StringWriter(); // first write to String Model p = MODEL_BUILDER.get(bean.getClass()); TreePruner pruner = (tree != null) ? new NamedPathPruner(tree) : new ByDepth(1 - depth); p.writeTo(bean, pruner, Flavor.XML.createDataWriter(bean, sw)); // apply XPath FilteredFunctionContext functionContext = new FilteredFunctionContext(); Object result; try { Document dom = new SAXReader().read(new StringReader(sw.toString())); // apply exclusions if (excludes != null) { for (String exclude : excludes) { XPath xExclude = dom.createXPath(exclude); xExclude.setFunctionContext(functionContext); List<org.dom4j.Node> list = (List<org.dom4j.Node>) xExclude.selectNodes(dom); for (org.dom4j.Node n : list) { Element parent = n.getParent(); if (parent != null) parent.remove(n); } } } if (xpath == null) { result = dom; } else { XPath comp = dom.createXPath(xpath); comp.setFunctionContext(functionContext); List list = comp.selectNodes(dom); if (wrapper != null) { Element root = DocumentFactory.getInstance().createElement(wrapper); for (Object o : list) { if (o instanceof String) { root.addText(o.toString()); } else { root.add(((org.dom4j.Node) o).detach()); } } result = root; } else if (list.isEmpty()) { rsp.setStatus(HttpServletResponse.SC_NOT_FOUND); rsp.getWriter().print(Messages.Api_NoXPathMatch(xpath)); return; } else if (list.size() > 1) { rsp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); rsp.getWriter().print(Messages.Api_MultipleMatch(xpath, list.size())); return; } else { result = list.get(0); } } } catch (DocumentException e) { LOGGER.log(Level.FINER, "Failed to do XPath/wrapper handling. XML is as follows:" + sw, e); throw new IOException("Failed to do XPath/wrapper handling. Turn on FINER logging to view XML.", e); } if (isSimpleOutput(result) && !permit(req)) { // simple output prohibited rsp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "primitive XPath result sets forbidden; implement jenkins.security.SecureRequester"); return; } // switch to gzipped output OutputStream o = rsp.getCompressedOutputStream(req); try { if (isSimpleOutput(result)) { // simple output allowed rsp.setContentType("text/plain;charset=UTF-8"); String text = result instanceof CharacterData ? ((CharacterData) result).getText() : result.toString(); o.write(text.getBytes("UTF-8")); return; } // otherwise XML rsp.setContentType("application/xml;charset=UTF-8"); new XMLWriter(o).write(result); } finally { o.close(); } }