List of usage examples for javax.xml.xpath XPathConstants NODESET
QName NODESET
To view the source code for javax.xml.xpath XPathConstants NODESET.
Click Source Link
The XPath 1.0 NodeSet data type.
Maps to Java org.w3c.dom.NodeList .
From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandler.java
/** * This method performs entity resolution and returns the Merge Response Document. * //ww w . j a v a 2s . co m * @param entityContainerNode * @param attributeParametersNode * @param entityResolutionConfigurationNode * @return * @throws Exception * @throws ParserConfigurationException * @throws XPathExpressionException */ Document performEntityResolution(Node entityContainerNode, Node attributeParametersNode, Node entityResolutionConfigurationNode) throws Exception, ParserConfigurationException, XPathExpressionException { Set<AttributeParametersXpathSupport> attributeParametersXpathSupport = getAttributeParameters( attributeParametersNode); // We can't call the ER OSGi service with AttributeParametersXpathSupport Set // so we create an attributeParameters Set to call it with. Set<AttributeParameters> attributeParameters = new HashSet<AttributeParameters>(); for (AttributeParametersXpathSupport attributeParameterXpathSupport : attributeParametersXpathSupport) { attributeParameters.add(attributeParameterXpathSupport); } String recordLimitString = null; if (entityResolutionConfigurationNode != null) { recordLimitString = xpath.evaluate("er-ext:RecordLimit", entityResolutionConfigurationNode); } int recordLimit = Integer.MAX_VALUE; if (recordLimitString != null) { try { recordLimit = Integer.parseInt(recordLimitString); } catch (NumberFormatException nfe) { LOG.debug("Record limit value " + recordLimitString + " does not parse as an integer, will not set a record limit"); } } EntityResolutionResults results = null; NodeList entityNodeList = (NodeList) xpath.evaluate("er-ext:Entity", entityContainerNode, XPathConstants.NODESET); if (entityNodeList.getLength() <= recordLimit) { List<RecordWrapper> records = createRecordsFromRequestMessage(entityNodeList, attributeParametersNode); LOG.debug("before resolveEntities, records=" + records); results = entityResolutionService.resolveEntities(records, attributeParameters, recordLimit); } Document resultDocument = createResponseMessage(entityContainerNode, results, attributeParametersNode, recordLimit); // without this next line, we get an exception about an unbound namespace URI (NIEM structures) resultDocument.normalizeDocument(); return resultDocument; }
From source file:org.eclipse.lyo.testsuite.oslcv2.CoreResourceXmlTests.java
@Test public void CoreResourceHasAtMostOneName() throws XPathExpressionException { String eval = "//" + getNode() + "/" + "dc:name"; NodeList names = (NodeList) OSLCUtils.getXPath().evaluate(eval, doc, XPathConstants.NODESET); assertTrue(getFailureMessage(), names.getLength() <= 1); }
From source file:dk.statsbiblioteket.doms.iprolemapper.webservice.IPRangesConfigReader.java
/** * This method produces an <code>IPRangeRoles</code> instance from the * information stored in the <code>Node</code> specified by * <code>ipRangeNode</code>. * //from w w w.ja v a 2 s .c o m * @param ipRangeNode * a <code>Document Node</code> containing information about an * IP range and its associated roles. * @return an <code>IPRangeRoles</code> instance created from the * information contained in <code>ipRangeNode</code>. * @throws XPathExpressionException * if any errors are encountered while reading range roles from * <code>ipRangeNode</code>. * @throws UnknownHostException * if the begin or end address of <code>ipRangeNode</code> is * either an unknown host name or an illegal IP address. * @throws IllegalArgumentException * if the begin address and end address of the range is not of * the same type. I.e. if they are not both IPv4 or IPv6 * addresses, or if <code>beginAddress</code> is higher/after * <code>endAddress</code>. */ private IPRangeRoles produceIPRangeInstance(Node ipRangeNode) throws XPathExpressionException, IllegalArgumentException, UnknownHostException { if (log.isTraceEnabled()) { String ipRangeNodeXMLString = "Malformed XML"; try { ipRangeNodeXMLString = DOM.domToString(ipRangeNode); } catch (TransformerException transformerException) { // Just ignore for now and log. The code will break later... } log.trace("produceIPRangeInstance(): Called with XML node: " + ipRangeNodeXMLString); } final NamedNodeMap attributes = ipRangeNode.getAttributes(); final String beginAddress = attributes.getNamedItem("begin").getNodeValue(); final String endAddress = attributes.getNamedItem("end").getNodeValue(); final XPathFactory xPathFactory = XPathFactory.newInstance(); final XPath xPath = xPathFactory.newXPath(); final NodeList ipRangeRoleNodes = (NodeList) xPath.evaluate("role", ipRangeNode, XPathConstants.NODESET); final List<String> ipRangeRoles = new LinkedList<String>(); for (int nodeIdx = 0; nodeIdx < ipRangeRoleNodes.getLength(); nodeIdx++) { ipRangeRoles.add(ipRangeRoleNodes.item(nodeIdx).getTextContent().trim()); } final IPRangeRoles rangeRoles = new IPRangeRoles(InetAddress.getByName(beginAddress), InetAddress.getByName(endAddress), ipRangeRoles); if (log.isTraceEnabled()) { log.trace("produceIPRangeInstance(): Returning IPRangeRoles " + "instance: " + rangeRoles); } return rangeRoles; }
From source file:org.eclipse.lyo.testsuite.oslcv2.cm.ChangeRequestXmlTests.java
@Test public void changeRequestHasAtMostOneIdentifier() throws XPathExpressionException { NodeList ids = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_cm_v2:ChangeRequest/dc:identifier", doc, XPathConstants.NODESET); assertTrue(getFailureMessage(), ids.getLength() <= 1); }
From source file:com.alvexcore.share.ShareExtensionRegistry.java
public ExtensionUpdateInfo checkForUpdates(String extensionId, String shareId, Map<String, String> shareHashes, String shareVersion, String repoId, Map<String, String> repoHashes, String repoVersion, String licenseId) throws Exception { // search for extension DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance(); xmlFact.setNamespaceAware(true);//from www. j a va 2 s .c o m xmlBuilder = xmlFact.newDocumentBuilder(); // build query Document queryXML = xmlBuilder.newDocument(); Element rootElement = queryXML.createElement("extension"); queryXML.appendChild(rootElement); Element el = queryXML.createElement("license-id"); el.appendChild(queryXML.createTextNode(licenseId)); rootElement.appendChild(el); el = queryXML.createElement("id"); el.appendChild(queryXML.createTextNode(extensionId)); rootElement.appendChild(el); el = queryXML.createElement("share-version"); el.appendChild(queryXML.createTextNode(shareVersion)); rootElement.appendChild(el); el = queryXML.createElement("repo-version"); el.appendChild(queryXML.createTextNode(repoVersion)); rootElement.appendChild(el); el = queryXML.createElement("share-id"); el.appendChild(queryXML.createTextNode(shareId)); rootElement.appendChild(el); el = queryXML.createElement("repo-id"); el.appendChild(queryXML.createTextNode(repoId)); rootElement.appendChild(el); el = queryXML.createElement("share-files"); rootElement.appendChild(el); for (String fileName : shareHashes.keySet()) { Element fileElem = queryXML.createElement("file"); fileElem.setAttribute("md5hash", shareHashes.get(fileName)); fileElem.appendChild(queryXML.createTextNode(fileName)); el.appendChild(fileElem); } el = queryXML.createElement("repo-files"); rootElement.appendChild(el); for (String fileName : repoHashes.keySet()) { Element fileElem = queryXML.createElement("file"); fileElem.setAttribute("md5hash", repoHashes.get(fileName)); fileElem.appendChild(queryXML.createTextNode(fileName)); el.appendChild(fileElem); } // query server try { URL url = new URL( "https://update.alvexhq.com:443/alfresco/s/api/alvex/extension/" + extensionId + "/update"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); // disable host verification conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); conn.setDoOutput(true); conn.setDoInput(true); conn.connect(); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); TransformerFactory.newInstance().newTransformer().transform(new DOMSource(queryXML), new StreamResult(wr)); wr.close(); // get response Document responseXML = xmlBuilder.parse(conn.getInputStream()); XPath xpath = XPathFactory.newInstance().newXPath(); // get version String repoLatestVersion = ((Node) xpath.evaluate("/extension/repo-version/text()", responseXML, XPathConstants.NODE)).getNodeValue(); String shareLatestVersion = ((Node) xpath.evaluate("/extension/share-version/text()", responseXML, XPathConstants.NODE)).getNodeValue(); NodeList nl = (NodeList) xpath.evaluate("/extension/repo-files/file", responseXML, XPathConstants.NODESET); Map<String, Boolean> repoFiles = new HashMap<String, Boolean>(nl.getLength()); for (int i = 0; i < nl.getLength(); i++) repoFiles.put(nl.item(i).getTextContent(), "ok".equals(nl.item(i).getAttributes().getNamedItem("status").getNodeValue())); nl = (NodeList) xpath.evaluate("/extension/share-files/file", responseXML, XPathConstants.NODESET); Map<String, Boolean> shareFiles = new HashMap<String, Boolean>(nl.getLength()); for (int i = 0; i < nl.getLength(); i++) shareFiles.put(nl.item(i).getTextContent(), "ok".equals(nl.item(i).getAttributes().getNamedItem("status").getNodeValue())); String motd = ((Node) xpath.evaluate("/extension/motd/text()", responseXML, XPathConstants.NODE)) .getNodeValue(); return new ExtensionUpdateInfo(extensionId, repoVersion, shareVersion, repoLatestVersion, shareLatestVersion, repoFiles, shareFiles, motd); } catch (Exception e) { return new ExtensionUpdateInfo(extensionId, repoVersion, shareVersion, "", "", new HashMap<String, Boolean>(), new HashMap<String, Boolean>(), ""); } }
From source file:com.hygenics.parser.ManualReplacement.java
private void transform() { log.info("Transforming"); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); for (String fpath : fpaths) { log.info("FILE: " + fpath); try {/* ww w . j a va 2 s . c o m*/ // TRANSFORM DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new File(fpath)); Node root = doc.getFirstChild(); XPathFactory xfactory = XPathFactory.newInstance(); XPath xpath = xfactory.newXPath(); String database = null; String path = "//transformation/connection"; log.info("Removing"); for (String dbname : remove) { log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]"); XPathExpression xepr = xpath .compile(path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]"); Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE); if (conn != null) { root.removeChild(conn); } } log.info("Transforming"); for (String key : databaseAttributes.keySet()) { database = key; log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + database.trim() + "')]]"); XPathExpression xepr = xpath .compile(path + "[descendant::name[contains(text(),'" + database.trim() + "')]]"); Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE); if (conn != null) { if (remove.contains(key)) { root.removeChild(conn); } else { Map<String, String> attrs = databaseAttributes.get(database); NodeList nl = conn.getChildNodes(); Set<String> keys = databaseAttributes.get(key).keySet(); for (int i = 0; i < nl.getLength(); i++) { org.w3c.dom.Node n = nl.item(i); if (keys.contains(n.getNodeName().trim())) { n.setNodeValue(attrs.get(n.getNodeName())); } } } } if (!this.log_to_table || (this.log_to_table && this.loggingTables != null)) { log.info("Logging Manipulation"); log.info("PERFORMING LOGGING MANIPULATION: " + (!this.log_to_table) != null ? "Removing Logging Data" : "Adding Logging data"); String[] sections = new String[] { "trans-log-table", "perf-log-table", "channel-log-table", "step-log-table", "metrics-log-table" }; for (String section : sections) { log.info("Changing Settings for " + section); xepr = xpath.compile("//" + section + "/field/enabled"); NodeList nodes = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET); log.info("Nodes Found: " + Integer.toString(nodes.getLength())); for (int i = 0; i < nodes.getLength(); i++) { if (!this.log_to_table) { nodes.item(i).setNodeValue("N"); } else { nodes.item(i).setNodeValue("Y"); } } for (String nodeName : new String[] { "schema", "connection", "table", "size_limit_lines", "interval", "timeout_days" }) { if (!this.log_to_table) { log.info("Changing Settings for Node: " + nodeName); xepr = xpath.compile("//" + section + "/" + nodeName); Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE); if (node != null) { if (!this.log_to_table) { node.setNodeValue(null); } else if (this.loggingTables.containsKey(section) && this.loggingTables.get(section).containsKey(nodeName)) { node.setNodeValue(this.loggingTables.get(section).get(nodeName)); } } } } } } } // SET MAIN CONNECTION if (mainConnection != null) { XPathExpression xepr = xpath.compile(path); NodeList conns = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET); // NodeSet is not a part of // org.w3c it is // actually a NodeList for (int i = 0; i < conns.getLength(); i++) { if (!conns.item(i).hasChildNodes()) {// only connection // elements // without child // nodes have // text content conns.item(i).setNodeValue(mainConnection); } } } if (this.replacements != null) { for (String key : this.replacements.keySet()) { XPathExpression xepr = xpath.compile(key); Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE); if (node != null) { for (String attrVal : this.replacements.get(key).keySet()) { log.info("Replacing Information at " + key + "at " + attrVal); log.info("Replacement Will Be: " + StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal))); if (attrVal.toLowerCase().trim().equals("text")) { node.setNodeValue( StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal))); if (node.getNodeValue() == null) { node.setTextContent(StringEscapeUtils .escapeXml11(this.replacements.get(key).get(attrVal))); } } else { NamedNodeMap nattrs = node.getAttributes(); Node n = nattrs.getNamedItem(attrVal); if (n != null) { n.setNodeValue(StringEscapeUtils .escapeXml11(this.replacements.get(key).get(attrVal))); } else { log.warn("Attribute Not Found " + attrVal); } } } } else { log.warn("Node not found for " + key); } } } // WRITE TO FILE log.info("Writing to File"); TransformerFactory tfact = TransformerFactory.newInstance(); Transformer transformer = tfact.newTransformer(); DOMSource source = new DOMSource(doc); try (FileOutputStream stream = new FileOutputStream(new File(fpath))) { StreamResult result = new StreamResult(stream); transformer.transform(source, result); stream.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } } }
From source file:com.inbravo.scribe.rest.service.crm.ZDRESTCRMService.java
@Override public final ScribeCommandObject getObjects(final ScribeCommandObject cADCommandObject) throws Exception { logger.debug("----Inside getObjects"); /* Check if all record types are to be searched */ if (cADCommandObject.getObjectType().trim().equalsIgnoreCase(HTTPConstants.anyObject)) { return this.searchAllTypeOfObjects(cADCommandObject, null, null, null); } else {/*w w w . j av a 2 s . com*/ GetMethod getMethod = null; try { String serviceURL = null; String serviceProtocol = null; String userId = null; String password = null; String crmPort = "80"; /* Check if agent is present in request */ if (cADCommandObject.getCrmUserId() != null) { /* Get agent from session manager */ final ScribeCacheObject cacheObject = zDCRMSessionManager .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId()); /* Get CRM information from agent */ serviceURL = cacheObject.getScribeMetaObject().getCrmServiceURL(); serviceProtocol = cacheObject.getScribeMetaObject().getCrmServiceProtocol(); userId = cacheObject.getScribeMetaObject().getCrmUserId(); password = cacheObject.getScribeMetaObject().getCrmPassword(); crmPort = cacheObject.getScribeMetaObject().getCrmPort(); } /* Create Zen desk URL */ final String zenDeskURL = serviceProtocol + "://" + serviceURL + "/" + cADCommandObject.getObjectType() + "s.xml"; logger.debug("----Inside getObjects zenDeskURL: " + zenDeskURL); /* Instantiate get method */ getMethod = new GetMethod(zenDeskURL); /* Set request content type */ getMethod.addRequestHeader("Content-Type", "application/xml"); getMethod.addRequestHeader("accept", "application/xml"); final HttpClient httpclient = new HttpClient(); /* Set credentials */ httpclient.getState().setCredentials(new AuthScope(serviceURL, this.validateCrmPort(crmPort)), new UsernamePasswordCredentials(userId, password)); /* Execute method */ int result = httpclient.executeMethod(getMethod); logger.debug("----Inside getObjects response code: " + result + " & body: " + getMethod.getResponseBodyAsString()); if (result == HttpStatus.SC_OK) { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document document = builder.parse(getMethod.getResponseBodyAsStream()); /* Create new XPath object to query XML document */ final XPath xpath = XPathFactory.newInstance().newXPath(); /* XPath Query for showing all nodes value */ final XPathExpression expr = xpath.compile( "/" + cADCommandObject.getObjectType() + "s/" + cADCommandObject.getObjectType()); /* Get node list from response document */ final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET); /* Create new Scribe object list */ final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>(); /* Iterate over node list */ for (int i = 0; i < nodeList.getLength(); i++) { /* Create list of elements */ final List<Element> elementList = new ArrayList<Element>(); /* Get node from node list */ final Node node = nodeList.item(i); /* Create new Scribe object */ final ScribeObject cADbject = new ScribeObject(); /* Check if node has child nodes */ if (node.hasChildNodes()) { final NodeList subNodeList = node.getChildNodes(); /* Iterate over sub node list and create elements */ for (int j = 0; j < subNodeList.getLength(); j++) { final Node subNode = subNodeList.item(j); /* This trick is to avoid empty nodes */ if (!subNode.getNodeName().contains("#text")) { /* Create element from response */ final Element element = ZDCRMMessageFormatUtils .createMessageElement(subNode.getNodeName(), subNode.getTextContent()); /* Add element in list */ elementList.add(element); } } } /* Add all CRM fields */ cADbject.setXmlContent(elementList); /* Add Scribe object in list */ cADbjectList.add(cADbject); } /* Check if no record found */ if (cADbjectList.size() == 0) { throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zendesk"); } /* Set the final object in command object */ cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()])); } else if (result == HttpStatus.SC_FORBIDDEN) { throw new ScribeException(ScribeResponseCodes._1020 + "Query is forbidden by Zendesk CRM"); } else if (result == HttpStatus.SC_BAD_REQUEST) { throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request content"); } else if (result == HttpStatus.SC_UNAUTHORIZED) { throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM"); } else if (result == HttpStatus.SC_NOT_FOUND) { throw new ScribeException( ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM"); } } catch (final ScribeException exception) { throw exception; } catch (final ParserConfigurationException exception) { throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM", exception); } catch (final SAXException exception) { throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM", exception); } catch (final IOException exception) { throw new ScribeException( ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM", exception); } finally { /* Release connection socket */ if (getMethod != null) { getMethod.releaseConnection(); } } return cADCommandObject; } }
From source file:de.slub.fedora.oai.OaiHarvester.java
private void handleXmlResult(InputStream content) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); Document document = documentBuilderFactory.newDocumentBuilder().parse(content); XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression xSelectIdentifier = xPath.compile("//header/identifier"); NodeList nodes = (NodeList) xSelectIdentifier.evaluate(document, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i);/*from w ww .j av a 2 s.c o m*/ jobQueue.add(new ObjectIndexJob(IndexJob.Type.CREATE, getLocalIdentifier(n.getTextContent()))); } XPathExpression xSelectResumptionToken = xPath.compile("//resumptionToken"); resumptionToken = (String) xSelectResumptionToken.evaluate(document, XPathConstants.STRING); XPathExpression xSelectExpirationDate = xPath.compile("//resumptionToken/@expirationDate"); String s = (String) xSelectExpirationDate.evaluate(document, XPathConstants.STRING); if (s == null || s.isEmpty()) { expirationDate = null; } else { expirationDate = DatatypeConverter.parseDateTime(s).getTime(); } }
From source file:com.dianping.zebra.shard.jdbc.base.MultiDBBaseTestCase.java
private void parseCreateScriptConfigFile() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document configDoc = builder//from ww w . j ava 2 s. c o m .parse(MultiDBBaseTestCase.class.getClassLoader().getResourceAsStream(getCreateScriptConfigFile())); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); NodeList databaseList = (NodeList) xpath.compile("/databases/database").evaluate(configDoc, XPathConstants.NODESET); for (int i = 0; i < databaseList.getLength(); i++) { MultiCreateTableScriptEntry entry = new MultiCreateTableScriptEntry(); Element ele = (Element) databaseList.item(i); entry.setDbName(ele.getAttribute("name")); NodeList tableList = (NodeList) xpath.compile("tables/table").evaluate(ele, XPathConstants.NODESET); Map<String, String> map = new HashMap<String, String>(); for (int j = 0; j < tableList.getLength(); j++) { Element tableEle = (Element) tableList.item(j); map.put(tableEle.getAttribute("name"), tableEle.getTextContent()); } entry.setTableNameScriptMapping(map); createdTableList.add(entry); } }
From source file:cc.siara.csv_ml_demo.MainActivity.java
/** * Evaluates given XPath from Input box against Document generated by * parsing csv_ml in input box and sets value or node list to output box. *//*from w ww. jav a 2s.com*/ void processXPath() { EditText etInput = (EditText) findViewById(R.id.etInput); EditText etXPath = (EditText) findViewById(R.id.etXPath); CheckBox cbPretty = (CheckBox) findViewById(R.id.cbPretty); XPath xpath = XPathFactory.newInstance().newXPath(); MultiLevelCSVParser parser = new MultiLevelCSVParser(); Document doc = null; try { doc = parser.parseToDOM(new StringReader(etInput.getText().toString()), false); } catch (IOException e1) { e1.printStackTrace(); } if (doc == null) return; StringBuffer out_str = new StringBuffer(); try { XPathExpression expr = xpath.compile(etXPath.getText().toString()); try { Document outDoc = Util.parseXMLToDOM("<output></output>"); Element rootElement = outDoc.getDocumentElement(); NodeList ret = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < ret.getLength(); i++) { Object o = ret.item(i); if (o instanceof String) { out_str.append(o); } else if (o instanceof Node) { Node n = (Node) o; short nt = n.getNodeType(); switch (nt) { case Node.TEXT_NODE: case Node.ATTRIBUTE_NODE: case Node.CDATA_SECTION_NODE: // Only one value gets // evaluated? if (out_str.length() > 0) out_str.append(','); if (nt == Node.ATTRIBUTE_NODE) out_str.append(n.getNodeValue()); else out_str.append(n.getTextContent()); break; case Node.ELEMENT_NODE: rootElement.appendChild(outDoc.importNode(n, true)); break; } } } if (out_str.length() > 0) { rootElement.setTextContent(out_str.toString()); out_str.setLength(0); } out_str.append(Util.docToString(outDoc, true)); } catch (Exception e) { // Thrown most likely because the given XPath evaluates to a // string out_str.append(expr.evaluate(doc)); } } catch (XPathExpressionException e) { e.printStackTrace(); } if (out_str.length() > 5 && out_str.substring(0, 5).equals("<?xml")) out_str.delete(0, out_str.indexOf(">") + 1); EditText etOutput = (EditText) findViewById(R.id.etOutput); etOutput.setText(out_str.toString()); // tfOutputSize.setText(String.valueOf(xmlString.length())); }