List of usage examples for javax.xml.xpath XPathConstants NODE
QName NODE
To view the source code for javax.xml.xpath XPathConstants NODE.
Click Source Link
The XPath 1.0 NodeSet data type.
From source file:org.directwebremoting.drapgen.generate.gi.GiType.java
/** * Find implementing functions/*from w ww .j a v a 2 s. com*/ * <method access="public" id="method:setEnabled" name="setEnabled">... * @param name A method name to find in the input document * @return the node that matches the given name */ public GiMethod getImplementationDeclaration(String name) { try { XPathExpression implementationFinder = xpath.compile("//method[@name='" + name + "']"); return new GiMethod((Element) implementationFinder.evaluate(document, XPathConstants.NODE), getClassName()); } catch (XPathExpressionException ex) { throw new RuntimeException(ex); } }
From source file:org.dita.dost.util.DitaUtil.java
private static String getFileNameFromMap(String ditaMapPath) { StringBuffer fileName = new StringBuffer(); try {/*from w w w . jav a 2 s .co m*/ FileInputStream ditaMapStream; ditaMapStream = new FileInputStream(ditaMapPath); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); factory.setFeature("http://xml.org/sax/features/namespaces", false); factory.setFeature("http://xml.org/sax/features/validation", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder builder; Document doc = null; XPathExpression expr = null; builder = factory.newDocumentBuilder(); doc = builder.parse(new InputSource(ditaMapStream)); XPathFactory xFactory = XPathFactory.newInstance(); XPath xpath = xFactory.newXPath(); expr = xpath.compile("//bookmap/bookmeta/prodinfo/prodname"); Node prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE); if (prodNameNode != null) { fileName.append(prodNameNode.getTextContent()); expr = xpath.compile("//bookmap/bookmeta/prodinfo/vrmlist"); Element vrmlistNode = (Element) expr.evaluate(doc, XPathConstants.NODE); if (vrmlistNode != null) { NodeList versions = vrmlistNode.getElementsByTagName("vrm"); if (versions.getLength() > 0) { NamedNodeMap versionAttributes = versions.item(0).getAttributes(); Attr releaseAttr = (Attr) versionAttributes.getNamedItem("release"); if (releaseAttr != null) { fileName.append(String.format("_%s", releaseAttr.getValue())); } Attr versionAttr = (Attr) versionAttributes.getNamedItem("version"); if (versionAttr != null) { fileName.append(String.format("_%s", versionAttr.getValue())); } } } } else { expr = xpath.compile("/bookmap"); prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE); if (prodNameNode != null) { Node node = prodNameNode.getAttributes().getNamedItem("id"); if (node != null) { fileName.append(node.getTextContent()); } } else { expr = xpath.compile("/map"); prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE); if (prodNameNode != null) { Node node = prodNameNode.getAttributes().getNamedItem("title"); if (node != null) { fileName.append(node.getTextContent()); } } } } } catch (FileNotFoundException e) { } catch (ParserConfigurationException e) { } catch (SAXException e) { } catch (IOException e) { } catch (XPathExpressionException e) { } return fileName.toString(); }
From source file:org.docx4j.openpackaging.parts.XmlPart.java
/** * Set the value of the node referenced in the xpath expression. * //from w w w .j ava 2s .co m * @param xpath * @param value * @param prefixMappings a string such as "xmlns:ns0='http://schemas.medchart'" * @return * @throws Docx4JException */ public boolean setNodeValueAtXPath(String xpath, String value, String prefixMappings) throws Docx4JException { try { getNamespaceContext().registerPrefixMappings(prefixMappings); Node n = (Node) xPath.evaluate(xpath, doc, XPathConstants.NODE); if (n == null) { log.debug("xpath returned null"); return false; } log.debug(n.getClass().getName()); // Method 1: Crimson throws error // Could avoid with System.setProperty("javax.xml.parsers.DocumentBuilderFactory", // "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); //n.setTextContent(value); // Method 2: crimson ignores // n.setNodeValue(value); // Method 3: createTextNode, then append it // First, need to delete/replace existing text node if (n.getChildNodes() != null && n.getChildNodes().getLength() > 0) { NodeList nodes = n.getChildNodes(); for (int i = nodes.getLength(); i > 0; i--) { n.removeChild(nodes.item(i - 1)); } } Text t = n.getOwnerDocument().createTextNode(value); n.appendChild(t); // cache is now invalid return true; } catch (Exception e) { throw new Docx4JException("Problem setting value at xpath " + xpath); } }
From source file:org.dspace.content.authority.DSpaceControlledVocabulary.java
@Override public String getLabel(String field, String key, String locale) { init();/*from w w w . j a v a 2 s . c o m*/ String xpathExpression = String.format(idTemplate, key); XPath xpath = XPathFactory.newInstance().newXPath(); try { Node node = (Node) xpath.evaluate(xpathExpression, vocabulary, XPathConstants.NODE); return node.getAttributes().getNamedItem("label").getNodeValue(); } catch (XPathExpressionException e) { return (""); } }
From source file:org.easyrec.service.core.impl.ProfileServiceImpl.java
/** * Used// w w w .j av a 2s . c o m * @param tenantId * @param itemId * @param itemTypeId * @param dimensionXPath * @param value * */ @Override public synchronized boolean storeProfileField(Integer tenantId, String itemId, String itemTypeId, String dimensionXPath, String value) throws Exception { int itemIntID = idMappingDAO.lookup(itemId); XPathFactory xpf = XPathFactory.newInstance(); // load and parse the profile Document doc = getProfileXMLDocument(tenantId, itemIntID, itemTypeId); // follow the XPath from bottom to top until you find the first existing path element XPath xp = xpf.newXPath(); String tmpPath = dimensionXPath; NodeList nodeList = (NodeList) xp.evaluate(tmpPath, doc, XPathConstants.NODESET); if (nodeList.getLength() > 1) throw new MultipleProfileFieldsFoundException(nodeList.getLength() + " nodes found."); Node node = null; if (nodeList.getLength() == 1) nodeList.item(0).setTextContent(value); else { while (node == null) { tmpPath = dimensionXPath.substring(0, tmpPath.lastIndexOf("/")); if ("".equals(tmpPath)) tmpPath = "/"; node = (Node) xp.evaluate(tmpPath, doc, XPathConstants.NODE); } insertElement(doc, node, dimensionXPath.substring(tmpPath.length()), value); } StringWriter writer = new StringWriter(); Result result = new StreamResult(writer); trans.transform(new DOMSource(doc), result); writer.close(); String xml = writer.toString(); logger.debug(xml); storeProfile(tenantId, itemId, itemTypeId, xml); return true; }
From source file:org.easyrec.service.domain.profile.impl.ProfileServiceImpl.java
public void insertOrUpdateMultiDimension(Integer tenantId, Integer itemId, String itemTypeId, String dimensionXPath, List<String> values) { XPathFactory xpf = XPathFactory.newInstance(); try {//from w ww . jav a 2s. c om // load and parse the profile DocumentBuilder db = validationParsers.get(tenantId).get(itemTypeId); Document doc = db.parse(new InputSource(new StringReader(getProfile(tenantId, itemId, itemTypeId)))); // check if the element exists Node node = null; Node parent = null; XPath xp = xpf.newXPath(); for (Iterator<String> it = values.iterator(); it.hasNext();) { String value = it.next(); // look if value already exists node = (Node) xp.evaluate(dimensionXPath + "[text()='" + value + "']", doc, XPathConstants.NODE); // if value exists, value can be discarded if (node != null) { // optimization: if a node was found, store the parent; later no new XPath evaluation is necessary parent = node.getParentNode(); it.remove(); } } if (values.isEmpty()) return; // nothing left to do String parentPath = dimensionXPath.substring(0, dimensionXPath.lastIndexOf("/")); // find path to parent if (parent == null) { String tmpPath = parentPath; while (parent == null) { tmpPath = parentPath.substring(0, tmpPath.lastIndexOf("/")); parent = (Node) xp.evaluate(tmpPath, doc, XPathConstants.NODE); } parent = insertElement(doc, parent, parentPath.substring(tmpPath.length()), null); } String tag = dimensionXPath.substring(parentPath.length() + 1); for (String value : values) { Element el = doc.createElement(tag); el.setTextContent(value); parent.appendChild(el); } StringWriter writer = new StringWriter(); Result result = new StreamResult(writer); trans.transform(new DOMSource(doc), result); writer.close(); String xml = writer.toString(); logger.debug(xml); storeProfile(tenantId, itemId, itemTypeId, xml, true); } catch (Exception e) { logger.error("Error inserting Multi Dimension: " + e.getMessage()); e.printStackTrace(); } }
From source file:org.easyrec.service.domain.profile.impl.ProfileServiceImpl.java
public void insertOrUpdateSimpleDimension(Integer tenantId, Integer itemId, String itemTypeId, String dimensionXPath, String value) { XPathFactory xpf = XPathFactory.newInstance(); try {/*from w w w. j ava2 s. c om*/ // load and parse the profile DocumentBuilder db = validationParsers.get(tenantId).get(itemTypeId); Document doc = db.parse(new InputSource(new StringReader(getProfile(tenantId, itemId, itemTypeId)))); // check if the element exists XPath xp = xpf.newXPath(); Node node = (Node) xp.evaluate(dimensionXPath, doc, XPathConstants.NODE); // if the element exists, just update the value if (node != null) { // if value doesn't change, there is no need to alter the profile and write it to database if (value.equals(node.getTextContent())) return; node.setTextContent(value); } else { // if the element cannot be found, insert it at the position given in the dimensionXPath // follow the XPath from bottom to top until you find the first existing path element String tmpPath = dimensionXPath; while (node == null) { tmpPath = dimensionXPath.substring(0, tmpPath.lastIndexOf("/")); node = (Node) xp.evaluate(tmpPath, doc, XPathConstants.NODE); } // found the correct node to insert or ended at Document root, hence insert insertElement(doc, node, dimensionXPath.substring(tmpPath.length()/*, dimensionXPath.length()*/), value); } StringWriter writer = new StringWriter(); Result result = new StreamResult(writer); trans.transform(new DOMSource(doc), result); writer.close(); String xml = writer.toString(); logger.debug(xml); storeProfile(tenantId, itemId, itemTypeId, xml, true); } catch (Exception e) { logger.error("Error inserting Simple Dimension: " + e.getMessage()); e.printStackTrace(); } }
From source file:org.eclipse.lyo.testsuite.oslcv2.asset.GetAndUpdateXmlTests.java
private NodeList getAssetNodeChildren(Document document) throws XPathExpressionException { String path = "/rdf:RDF/oslc_asset:Asset"; XPath xpath = OSLCUtils.getXPath(); Node asset = (Node) xpath.evaluate(path, document, XPathConstants.NODE); return asset.getChildNodes(); }
From source file:org.eclipse.lyo.testsuite.oslcv2.asset.UsageCaseXmlTests.java
@Test public void publishUsageCase() throws IOException, ParseException, ParserConfigurationException, SAXException, TransformerException, XPathException { // Get url// www . j ava 2s . c om ArrayList<String> serviceUrls = getServiceProviderURLsUsingXML(setupProps.getProperty("baseUri")); ArrayList<String> capabilityURLsUsingRdfXml = TestsBase.getCapabilityURLsUsingRdfXml( OSLCConstants.CREATION_PROP, serviceUrls, useDefaultUsageForCreation, null); currentUrl = capabilityURLsUsingRdfXml.get(0); // Create the asset assetUrl = createAsset(xmlCreateTemplate); assertTrue("The location of the asset after it was create was not returned", assetUrl != null); // Add the artifact to the asset String artifactFactory = getArtifactFactory(); Header[] header = addHeader(new BasicHeader("oslc_asset.name", "/helpFolder/help")); //String fileName = setupProps.getProperty("createTemplateArtifactXmlFile"); String fileName = setupProps.getProperty("createTemplateXmlFile"); assertTrue("There needs to be an artifact template file", fileName != null); String artifact = OSLCUtils.readFileByNameAsString(fileName); HttpResponse response = OSLCUtils.postDataToUrl(artifactFactory, creds, OSLCConstants.CT_XML, OSLCConstants.CT_XML, artifact, header); EntityUtils.consume(response.getEntity()); assertTrue("Expected " + HttpStatus.SC_OK + ", received " + response.getStatusLine().getStatusCode(), response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED); // Get updated asset and update the artifact HttpResponse resp = getAssetResponse(); String content = EntityUtils.toString(resp.getEntity()); Document document = OSLCUtils.createXMLDocFromResponseBody(content); EntityUtils.consume(resp.getEntity()); String path = "/rdf:RDF/oslc_asset:Asset/oslc_asset:artifact[1]/oslc_asset:Artifact"; XPath xpath = OSLCUtils.getXPath(); Node artifactNode = (Node) xpath.evaluate(path, document, XPathConstants.NODE); NodeList artifactKids = artifactNode.getChildNodes(); Node label = null; for (int i = 0; i < artifactKids.getLength(); i++) { if (artifactKids.item(i).getNodeName().equals("oslc:label")) { label = artifactKids.item(i); break; } } String labelValue = "this value was changed"; if (label == null) { label = document.createElement("oslc:label"); label.setTextContent(labelValue); artifactNode.appendChild(label); } else { label.setTextContent(labelValue); } // Update asset content = OSLCUtils.createStringFromXMLDoc(document); putAsset(content); // Check to see if the label was updated resp = getAssetResponse(); content = EntityUtils.toString(resp.getEntity()); document = OSLCUtils.createXMLDocFromResponseBody(content); EntityUtils.consume(resp.getEntity()); path = "/rdf:RDF/oslc_asset:Asset/oslc_asset:artifact[1]/oslc_asset:Artifact/oslc:label"; xpath = OSLCUtils.getXPath(); label = (Node) xpath.evaluate(path, document, XPathConstants.NODE); assertTrue("Could not find the artifact's label node", label != null); assertEquals("The label was not updated properly", labelValue, label.getTextContent()); }
From source file:org.eclipse.lyo.testsuite.oslcv2.asset.UsageCaseXmlTests.java
private void retrieveArtifact(String asset) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException { Document document = OSLCUtils.createXMLDocFromResponseBody(asset); String path = "/rdf:RDF/oslc_asset:Asset/oslc_asset:artifact[1]/oslc_asset:Artifact/oslc_asset:content"; XPath xpath = OSLCUtils.getXPath(); Node content = (Node) xpath.evaluate(path, document, XPathConstants.NODE); assertTrue("Could not find the artifact", content != null); NamedNodeMap attributes = content.getAttributes(); String artifactUrl = attributes.getNamedItem("rdf:resource").getNodeValue(); assertTrue("No artifact could be found in the asset", artifactUrl != null); HttpResponse resp = OSLCUtils.getDataFromUrl(artifactUrl, creds, acceptType, contentType, headers); EntityUtils.consume(resp.getEntity()); assertTrue("Expected " + HttpStatus.SC_OK + ", received " + resp.getStatusLine().getStatusCode(), resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK); }