Example usage for javax.xml.xpath XPathFactory newXPath

List of usage examples for javax.xml.xpath XPathFactory newXPath

Introduction

In this page you can find the example usage for javax.xml.xpath XPathFactory newXPath.

Prototype

public abstract XPath newXPath();

Source Link

Document

Return a new XPath using the underlying object model determined when the XPathFactory was instantiated.

Usage

From source file:org.openhab.tools.analysis.checkstyle.api.AbstractStaticCheck.java

/**
 * Compiles an XPathExpression/*ww  w . j  a  va 2  s.  c om*/
 *
 * @param expresion - the XPath expression
 * @return compiled XPath expression
 * @throws CheckstyleException if an error occurred during the compilation
 */
protected XPathExpression compileXPathExpression(String expresion) throws CheckstyleException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    try {
        return xpath.compile(expresion);
    } catch (XPathExpressionException e) {
        throw new CheckstyleException("Unable to compile the expression" + expresion, e);
    }
}

From source file:org.overlord.sramp.common.artifactbuilder.XmlArtifactBuilder.java

@Override
public ArtifactBuilder buildArtifacts(BaseArtifactType primaryArtifact, ArtifactContent artifactContent)
        throws IOException {
    super.buildArtifacts(primaryArtifact, artifactContent);

    try {/*from w ww.  ja v  a  2 s  . com*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); //$NON-NLS-1$
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); //$NON-NLS-1$

        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(getContentStream());
        // This *must* be setup prior to calling #configureNamespaceMappings.  Most subclasses will need it.
        rootElement = document.getDocumentElement();

        if (primaryArtifact instanceof XmlDocument) {
            String encoding = document.getXmlEncoding();
            if (StringUtils.isBlank(encoding)) {
                encoding = "UTF-8";
            }
            ((XmlDocument) primaryArtifact).setContentEncoding(encoding);
        }

        XPathFactory xPathfactory = XPathFactory.newInstance();
        xpath = xPathfactory.newXPath();
        StaticNamespaceContext nsCtx = new StaticNamespaceContext();
        configureNamespaceMappings(nsCtx);
        xpath.setNamespaceContext(nsCtx);

        // Create all derived artifacts
        derive();

        // Set the relatedDocument relationship for all derived artifacts
        for (BaseArtifactType derivedArtifact : getDerivedArtifacts()) {
            if (derivedArtifact instanceof DerivedArtifactType) {
                DerivedArtifactType dat = (DerivedArtifactType) derivedArtifact;
                if (dat.getRelatedDocument() == null) {
                    DocumentArtifactTarget related = new DocumentArtifactTarget();
                    related.setValue(primaryArtifact.getUuid());
                    related.setArtifactType(DocumentArtifactEnum.fromValue(primaryArtifact.getArtifactType()));
                    dat.setRelatedDocument(related);
                }
            } else {
                Relationship genericRelationship = SrampModelUtils.getGenericRelationship(derivedArtifact,
                        "relatedDocument"); //$NON-NLS-1$
                if (genericRelationship == null) {
                    SrampModelUtils.addGenericRelationship(derivedArtifact, "relatedDocument", //$NON-NLS-1$
                            primaryArtifact.getUuid());
                }
            }
        }

        return this;
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:org.photovault.geocoding.OSMGeocoder.java

public OSMGeocoder() {
    XPathFactory xpf = XPathFactory.newInstance();
    XPath path = xpf.newXPath();
    try {//from   w w  w  .  j  ava2s . c o m
        reverseAddrExpr = path.compile("/reversegeocode/result/text()");
        reverseHouseExpr = path.compile("/reversegeocode/addressparts/house/text()");
        reverseRoadExpr = path.compile("/reversegeocode/addressparts/road/text()");
        reverseSuburbExpr = path.compile("/reversegeocode/addressparts/suburb/text()");
        reverseCityExpr = path.compile("/reversegeocode/addressparts/city/text()");
        reverseCountryExpr = path.compile("/reversegeocode/addressparts/country/text()");
        reverseCountryCodeExpr = path.compile("/reversegeocode/addressparts/country_code/text()");
    } catch (XPathExpressionException e) {
        log.error(e);
    }
}

From source file:org.photovault.geocoding.OSMGeocoder.java

private List<Location> parsePlaces(Document doc) {
    List<Location> ret = new ArrayList();
    XPathFactory xpf = XPathFactory.newInstance();
    XPath nodesPath = xpf.newXPath();
    try {/*from  w  w w  .  ja  va2s .c om*/
        NodeList placeNodes = (NodeList) nodesPath.evaluate("/searchresults/place", doc,
                XPathConstants.NODESET);
        for (int n = 0; n < placeNodes.getLength(); n++) {
            Location loc = new Location();
            Node placeNode = placeNodes.item(n);
            String road = nodesPath.evaluate("//road/text()", placeNode);
            String suburb = nodesPath.evaluate("//suburb/text()", placeNode);
            String city = nodesPath.evaluate("//city/text()", placeNode);
            String county = nodesPath.evaluate("//county/text()", placeNode);
            String country = nodesPath.evaluate("//country/text()", placeNode);
            String countryCode = nodesPath.evaluate("//country_code/text()", placeNode);
            String latStr = nodesPath.evaluate("@lat", placeNode);
            String lonStr = nodesPath.evaluate("@lon", placeNode);
            String desc = nodesPath.evaluate("@display_name", placeNode);
            loc.setRoad(road);
            loc.setSuburb(suburb);
            loc.setCity(city);
            loc.setCountry(country);
            loc.setCountryCode(countryCode);
            double lat = Double.parseDouble(latStr);
            double lon = Double.parseDouble(lonStr);
            GeoHash geohash = GeoHash.withBitPrecision(lat, lon, 60);
            loc.setCoordinate(geohash);
            ret.add(loc);
        }

    } catch (XPathExpressionException e) {
        log.error(e);
    }
    return ret;

}

From source file:org.powertac.server.CompetitionSetupService.java

/**
 * Sets up the simulator, with config overrides provided in a file.
 *//* w  w  w .  ja v  a2 s.  c o m*/
public boolean preGame(URL bootFile) {
    log.info("preGame(File) - start");
    // run the basic pre-game setup
    preGame();

    // read the config info from the bootReader - We need to find a Competition
    Competition bootstrapCompetition = null;
    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    try {
        // first grab the Competition
        XPathExpression exp = xPath.compile("/powertac-bootstrap-data/config/competition");
        NodeList nodes = (NodeList) exp.evaluate(new InputSource(bootFile.openStream()),
                XPathConstants.NODESET);
        String xml = nodeToString(nodes.item(0));
        bootstrapCompetition = (Competition) messageConverter.fromXML(xml);
    } catch (XPathExpressionException xee) {
        log.error("preGame: Error reading boot dataset: " + xee.toString());
        System.out.println("preGame: Error reading boot dataset: " + xee.toString());
        return false;
    } catch (IOException ioe) {
        log.error("preGame: Error opening file " + bootFile + ": " + ioe.toString());
        System.out.println("preGame: Error opening file " + bootFile + ": " + ioe.toString());
        return false;
    }
    // update the existing Competition - should be the current competition
    Competition.currentCompetition().update(bootstrapCompetition);
    return true;
}

From source file:org.rdswicthboard.utils.rdf.oai.App.java

public static void main(String[] args) {
    // create the command line parser
    CommandLineParser parser = new DefaultParser();

    // create the Options
    Options options = new Options();
    options.addOption("i", PROPERTY_INPUT_FILE, true, "input RDF file");
    options.addOption("o", PROPERTY_OUTPUT_FILE, true,
            "output OAI-PMH XML file (default is " + DEFAULT_OUTPUT_FILE + ")");
    options.addOption("c", PROPERTY_CONFIG_FILE, true, "configuration file (" + PROPERTIES_FILE + ")");
    options.addOption("s", PROPERTY_SET_SPEC, true, "set spec value (default is " + DEFAULT_SET_SPEC + ")");
    options.addOption("I", PROPERTY_INPUT_ENCODING, true,
            "input file encoding (default is " + DEFAULT_ENCODING + ")");
    options.addOption("O", PROPERTY_OUTPUT_ENCODING, true,
            "output file encoding (default is " + DEFAULT_ENCODING + ")");
    options.addOption("f", PROPERTY_FORMAT_OUTPUT, false, "format output encoding");
    options.addOption("h", PROPERTY_HELP, false, "print this message");

    try {//w  ww .j  a v  a2  s  .c om
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption(PROPERTY_HELP)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar rdf2oai-[verion].jar [PARAMETERS] [INPUT FILE] [OUTPUT FILE]",
                    options);

            System.exit(0);
        }

        // variables to store program properties
        CompositeConfiguration config = new CompositeConfiguration();
        config.setProperty(PROPERTY_OUTPUT_FILE, DEFAULT_OUTPUT_FILE);
        config.setProperty(PROPERTY_INPUT_ENCODING, DEFAULT_ENCODING);
        config.setProperty(PROPERTY_OUTPUT_ENCODING, DEFAULT_ENCODING);
        config.setProperty(PROPERTY_SET_SPEC, DEFAULT_SET_SPEC);
        config.setProperty(PROPERTY_FORMAT_OUTPUT, DEFAULT_FORMAT_OUTPUT);

        // check if arguments has input file properties 
        if (line.hasOption(PROPERTY_CONFIG_FILE)) {
            // if it does, load the specified configuration file
            Path defaultConfig = Paths.get(line.getOptionValue(PROPERTY_CONFIG_FILE));
            if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) {
                config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile()));
            } else
                throw new Exception("Invalid configuration file: " + defaultConfig.toString());
        } else {
            // if it not, try to load default configurationfile
            Path defaultConfig = Paths.get(PROPERTIES_FILE);
            if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) {
                config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile()));
            }
        }

        // check if arguments has input file 
        if (line.hasOption(PROPERTY_INPUT_FILE))
            config.setProperty(PROPERTY_INPUT_FILE, line.getOptionValue(PROPERTY_INPUT_FILE));

        // check if arguments has output file
        if (line.hasOption(PROPERTY_OUTPUT_FILE))
            config.setProperty(PROPERTY_OUTPUT_FILE, line.getOptionValue(PROPERTY_OUTPUT_FILE));

        // check if arguments has set spec name
        if (line.hasOption(PROPERTY_SET_SPEC))
            config.setProperty(PROPERTY_SET_SPEC, line.getOptionValue(PROPERTY_SET_SPEC));

        // check if arguments has input encoding
        if (line.hasOption(PROPERTY_INPUT_ENCODING))
            config.setProperty(PROPERTY_INPUT_ENCODING, line.getOptionValue(PROPERTY_INPUT_ENCODING));

        // check if arguments has output encoding
        if (line.hasOption(PROPERTY_OUTPUT_ENCODING))
            config.setProperty(PROPERTY_OUTPUT_ENCODING, line.getOptionValue(PROPERTY_OUTPUT_ENCODING));

        // check if arguments has output encoding
        if (line.hasOption(PROPERTY_FORMAT_OUTPUT))
            config.setProperty(PROPERTY_FORMAT_OUTPUT, "yes");

        // check if arguments has input file without a key
        if (line.getArgs().length > 0) {
            config.setProperty(PROPERTY_INPUT_FILE, line.getArgs()[0]);

            // check if arguments has output file without a key
            if (line.getArgs().length > 1) {
                config.setProperty(PROPERTY_OUTPUT_FILE, line.getArgs()[1]);

                // check if there is too many arguments
                if (line.getArgs().length > 2)
                    throw new Exception("Too many arguments");
            }
        }

        // The program has default output file, but input file must be presented
        if (!config.containsKey(PROPERTY_INPUT_FILE))
            throw new Exception("Please specify input file");

        // extract input file
        String inputFile = config.getString(PROPERTY_INPUT_FILE);

        // extract output file
        String outputFile = config.getString(PROPERTY_OUTPUT_FILE);

        // extract set spec
        String setSpecName = config.getString(PROPERTY_SET_SPEC);

        // extract encoding
        String inputEncoding = config.getString(PROPERTY_INPUT_ENCODING);
        String outputEncoding = config.getString(PROPERTY_OUTPUT_ENCODING);

        boolean formatOutput = config.getBoolean(PROPERTY_FORMAT_OUTPUT);

        // test if source is an regular file and it is readable
        Path source = Paths.get(inputFile);
        if (!Files.isRegularFile(source))
            throw new Exception("The input file: " + source.toString() + " is not an regular file");
        if (!Files.isReadable(source))
            throw new Exception("The input file: " + source.toString() + " is not readable");

        Path target = Paths.get(outputFile);
        if (Files.exists(target)) {
            if (!Files.isRegularFile(target))
                throw new Exception("The output file: " + target.toString() + " is not an regular file");
            if (!Files.isWritable(target))
                throw new Exception("The output file: " + target.toString() + " is not writable");
        }

        // create and setup document builder factory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);

        // create new document builder
        DocumentBuilder builder = factory.newDocumentBuilder();

        // create oai document
        Document oai = builder.newDocument();

        // set document version
        oai.setXmlVersion("1.0");
        oai.setXmlStandalone(true);

        // create root OAI-PMH element
        Element oaiPmh = oai.createElement("OAI-PMH");

        // set document namespaces
        oaiPmh.setAttribute("xmlns", "http://www.openarchives.org/OAI/2.0/");
        oaiPmh.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi",
                "http://www.w3.org/2001/XMLSchema-instance");
        oaiPmh.setAttribute("xsi:schemaLocation",
                "http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd");

        // append root node
        oai.appendChild(oaiPmh);

        // create responseDate element
        Element responseDate = oai.createElement("responseDate");

        // create simple date format
        DateFormat dateFormat = new SimpleDateFormat(TIME_FORMAT);

        // generate date
        String date = dateFormat.format(new Date());

        // set current date and time
        responseDate.setTextContent(date);

        oaiPmh.appendChild(responseDate);

        Element listRecords = oai.createElement("ListRecords");
        oaiPmh.appendChild(listRecords);

        // create xpath factory
        XPathFactory xPathfactory = XPathFactory.newInstance();

        // create namespace context
        NamespaceContext namespaceContext = new NamespaceContext() {
            public String getNamespaceURI(String prefix) {
                if (prefix.equals("rdf"))
                    return RDF_NAMESPACE;
                else if (prefix.equals("rns"))
                    return RNF_NAMESPACE;
                else
                    return null;
            }

            @Override
            public Iterator<?> getPrefixes(String val) {
                throw new IllegalAccessError("Not implemented!");
            }

            @Override
            public String getPrefix(String uri) {
                throw new IllegalAccessError("Not implemented!");
            }
        };

        // create xpath object
        XPath xpath = xPathfactory.newXPath();
        // set namespace contex
        xpath.setNamespaceContext(namespaceContext);

        // create XPath expressions
        XPathExpression idExpr = xpath.compile("/rdf:RDF/rns:Researcher/@rdf:about");
        XPathExpression emptyExpr = xpath.compile("//text()[normalize-space(.) = '']");

        // create RegEx patterns  
        Pattern pattern = Pattern.compile(
                "<\\?xml\\s+version=\"[\\d\\.]+\"\\s*\\?>\\s*<\\s*rdf:RDF[^>]*>[\\s\\S]*?<\\s*\\/\\s*rdf:RDF\\s*>");

        // read file into a string
        String content = new String(Files.readAllBytes(source), inputEncoding);

        Matcher matcher = pattern.matcher(content);
        // process all records
        while (matcher.find()) {
            // convert string to input stream
            ByteArrayInputStream input = new ByteArrayInputStream(
                    matcher.group().getBytes(StandardCharsets.UTF_8.toString()));

            // parse the xml document
            Document doc = builder.parse(input);

            // remove all spaces
            NodeList emptyNodes = (NodeList) emptyExpr.evaluate(doc, XPathConstants.NODESET);
            // Remove each empty text node from document.
            for (int i = 0; i < emptyNodes.getLength(); i++) {
                Node emptyTextNode = emptyNodes.item(i);
                emptyTextNode.getParentNode().removeChild(emptyTextNode);
            }

            // obtain researcher id
            String id = (String) idExpr.evaluate(doc, XPathConstants.STRING);
            if (StringUtils.isEmpty(id))
                throw new Exception("The record identifier can not be empty");

            // create record element
            Element record = oai.createElement("record");
            listRecords.appendChild(record);

            // create header element
            Element header = oai.createElement("header");
            record.appendChild(header);

            // create identifier element
            Element identifier = oai.createElement("identifier");
            identifier.setTextContent(id);
            header.appendChild(identifier);

            // create datestamp element
            Element datestamp = oai.createElement("datestamp");
            datestamp.setTextContent(date);
            header.appendChild(datestamp);

            // create set spec element if it exists
            if (!StringUtils.isEmpty(setSpecName)) {
                Element setSpec = oai.createElement("setSpec");
                setSpec.setTextContent(setSpecName);
                header.appendChild(setSpec);
            }

            // create metadata element
            Element metadata = oai.createElement("metadata");
            record.appendChild(metadata);

            // import the record
            metadata.appendChild(oai.importNode(doc.getDocumentElement(), true));
        }

        // create transformer factory
        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        // create transformer
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding);

        if (formatOutput) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        } else
            transformer.setOutputProperty(OutputKeys.INDENT, "no");

        // create dom source
        DOMSource oaiSource = new DOMSource(oai);

        // create stream result
        StreamResult result = new StreamResult(target.toFile());

        // stream xml to file
        transformer.transform(oaiSource, result);

        // optional stream xml to console for testing
        //StreamResult consoleResult = new StreamResult(System.out);
        //transformer.transform(oaiSource, consoleResult);

    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());

        //e.printStackTrace();

        System.exit(1);
    }
}

From source file:org.red5.io.FileKeyFrameMetaCache.java

/** {@inheritDoc} */
public KeyFrameMeta loadKeyFrameMeta(File file) {
    String filename = file.getAbsolutePath() + ".meta";
    File metadataFile = new File(filename);
    if (!metadataFile.exists())
        // No such metadata
        return null;

    Document dom;/*from  w  w w . j  av a2 s  .c  o  m*/
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        // Using factory get an instance of document builder
        DocumentBuilder db = dbf.newDocumentBuilder();

        // parse using builder to get DOM representation of the XML file
        dom = db.parse(filename);
    } catch (ParserConfigurationException pce) {
        log.error("Could not parse XML file.", pce);
        return null;
    } catch (SAXException se) {
        log.error("Could not parse XML file.", se);
        return null;
    } catch (IOException ioe) {
        log.error("Could not parse XML file.", ioe);
        return null;
    }

    Element root = dom.getDocumentElement();
    // Check if .xml file is valid and for this .flv file
    if (!"FrameMetadata".equals(root.getNodeName()))
        // Invalid XML
        return null;

    String modified = root.getAttribute("modified");
    if (modified == null || !modified.equals(String.valueOf(file.lastModified())))
        // File has changed in the meantime
        return null;

    if (!root.hasAttribute("duration"))
        // Old file without duration informations
        return null;

    if (!root.hasAttribute("audioOnly"))
        // Old file without audio/video informations
        return null;

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    NodeList keyFrames;
    try {
        XPathExpression xexpr = xpath.compile("/FrameMetadata/KeyFrame");
        keyFrames = (NodeList) xexpr.evaluate(dom, XPathConstants.NODESET);
    } catch (XPathExpressionException err) {
        log.error("could not compile xpath expression", err);
        return null;
    }

    int length = keyFrames.getLength();
    if (keyFrames == null || length == 0)
        // File doesn't contain informations about keyframes
        return null;

    KeyFrameMeta result = new KeyFrameMeta();
    result.duration = Long.parseLong(root.getAttribute("duration"));
    result.positions = new long[length];
    result.timestamps = new int[length];
    for (int i = 0; i < length; i++) {
        Node node = keyFrames.item(i);
        NamedNodeMap attrs = node.getAttributes();
        result.positions[i] = Long.parseLong(attrs.getNamedItem("position").getNodeValue());
        result.timestamps[i] = Integer.parseInt(attrs.getNamedItem("timestamp").getNodeValue());
    }
    result.audioOnly = "true".equals(root.getAttribute("audioOnly"));

    return result;
}

From source file:org.rill.bpm.api.support.XpathVarConvertTaskLifecycleInterceptor.java

protected static void generateByXpath(Map<String, Object> workflowParams, String engineRelateDataname,
        Map<String, Object> convertAndFilter) {

    String expressionText = engineRelateDataname.substring(ENGINE_VARIABLE_DEFINITION_PREFIX.length());
    String[] split = StringUtils.delimitedListToStringArray(expressionText, ENGINE_VARIABLE_DEFINITION_SPLIT);
    if (split.length > 1 && workflowParams.containsKey(split[0]) && workflowParams.get(split[0]) != null
            && ClassUtils.isPrimitiveOrWrapper(workflowParams.get(split[0]).getClass())) {
        throw new ProcessException("Can not generate engine variable " + engineRelateDataname
                + " from workflow param" + workflowParams.get(split[0]));
    }//from w  ww .j av  a2  s  .com

    try {
        if (split.length > 1 && workflowParams.containsKey(split[0]) && workflowParams.get(split[0]) != null) {
            String workflowParamValue = (workflowParams.get(split[0]) instanceof String)
                    ? workflowParams.get(split[0]).toString()
                    : XStreamSerializeHelper.serializeXml(split[0], workflowParams.get(split[0]));
            log.debug("After XStream serialize :" + workflowParamValue);
            // Check it is XML or not
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new ByteArrayInputStream(workflowParamValue.getBytes("UTF-8")));
            XPathFactory xFactory = XPathFactory.newInstance();
            XPath xpath = xFactory.newXPath();
            StringBuilder sb = new StringBuilder();
            sb.append("//");
            for (int i = 1; i < split.length; i++) {
                sb.append(split[i]);
                sb.append("/");
            }
            sb.append("text()");
            log.debug("Build xPath:" + sb.toString());
            XPathExpression expr = xpath.compile(sb.toString());
            String value = (String) expr.evaluate(doc, XPathConstants.STRING);
            if (StringUtils.hasText(value.toString())) {
                log.debug("Parse xPath:" + sb.toString() + " and save value:" + value);
                convertAndFilter.put(engineRelateDataname, value);
            } else {
                log.warn("Can not get value using XPath because invalid engine data name: "
                        + engineRelateDataname);
            }
        } else {
            log.warn("Can not get value using XPath because invalid engine data name:" + engineRelateDataname);
        }
    } catch (Exception e) {
        log.warn("Exception occurred when parse expression using Xpath. Do next one.", e);
    }

}

From source file:org.rippleosi.patient.contacts.search.SCCISContactDetailsTransformer.java

@Override
public ContactDetails transform(Node xml) {

    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    ContactDetails contact = new ContactDetails();
    boolean foundContact = false;

    try {/*  w w  w.jav  a 2 s. co m*/
        // Search contacts from Carers section of XML
        NodeList nodeSet = (NodeList) xpath.evaluate("/LCR/Carers/List/RelatedPerson", xml,
                XPathConstants.NODESET);
        for (int i = 0; i < nodeSet.getLength(); i++) {
            Node node = nodeSet.item(i);
            String sourceId = (String) xpath.evaluate("identifier/value/@value", node, XPathConstants.STRING);

            if (sourceId.equalsIgnoreCase(contactId)) {

                contact.setSource("SC-CIS");

                String name = (String) xpath.evaluate("name/text/@value", node, XPathConstants.STRING);
                String relationshipTeam = (String) xpath.evaluate("relationship/coding/display/@value", node,
                        XPathConstants.STRING);
                String address = (String) xpath.evaluate("address/text/@value", node, XPathConstants.STRING);
                String phone = (String) xpath.evaluate("telecom[1]/value/@value", node, XPathConstants.STRING);

                contact.setSourceId(sourceId);
                contact.setName(name);
                contact.setRelationship(relationshipTeam);

                contact.setAddress(address);
                contact.setPhone(phone);
                contact.setAuthor("Adult Social Care System");
                foundContact = true;

                break;
            }

        }

        if (!foundContact) {
            // Search contacts from Allocations section of XML
            nodeSet = (NodeList) xpath.evaluate("/LCR/Allocations/List/Practitioner", xml,
                    XPathConstants.NODESET);
            for (int i = 0; i < nodeSet.getLength(); i++) {
                Node node = nodeSet.item(i);
                String sourceId = (String) xpath.evaluate("identifier/value/@value", node,
                        XPathConstants.STRING);

                if (sourceId.equalsIgnoreCase(contactId)) {

                    contact.setSource("SC-CIS");

                    String name = (String) xpath.evaluate("name/text/@value", node, XPathConstants.STRING);
                    String relationshipTeam = (String) xpath.evaluate(
                            "practitionerRole/role/coding/display/@value", node, XPathConstants.STRING);
                    String phone = (String) xpath.evaluate("telecom[1]/value/@value", node,
                            XPathConstants.STRING);

                    contact.setSourceId(sourceId);
                    contact.setName(name);
                    contact.setRelationship(relationshipTeam);

                    contact.setPhone(phone);
                    contact.setAuthor("Adult Social Care System");

                    break;
                }

            }
        }

    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    return contact;
}

From source file:org.rippleosi.patient.contacts.search.SCCISContactHeadlineTransformer.java

@Override
public List<ContactHeadline> transform(Node xml) {

    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();

    List<ContactHeadline> contactList = new ArrayList<ContactHeadline>();

    try {// w ww .j  a v a 2s  . com
        xml.normalize();
        // Retrieve contacts from Carers section of XML
        NodeList nodeSet = (NodeList) xpath.evaluate("/LCR/Carers/List/RelatedPerson", xml,
                XPathConstants.NODESET);
        for (int i = 0; i < nodeSet.getLength(); i++) {
            ContactHeadline contact = new ContactHeadline();
            contact.setSource("SC-CIS");

            Node node = nodeSet.item(i);
            String sourceId = (String) xpath.evaluate("identifier/value/@value", node, XPathConstants.STRING);
            String name = (String) xpath.evaluate("name/text/@value", node, XPathConstants.STRING);

            contact.setSourceId(sourceId);
            contact.setName(name);
            contactList.add(contact);
        }

        // Retrieve contacts from Allocations section of the XML
        nodeSet = (NodeList) xpath.evaluate("/LCR/Allocations/List/Practitioner", xml, XPathConstants.NODESET);

        for (int i = 0; i < nodeSet.getLength(); i++) {
            ContactHeadline contact = new ContactHeadline();
            contact.setSource("SC-CIS");

            Node node = nodeSet.item(i);
            String sourceId = (String) xpath.evaluate("identifier/value/@value", node, XPathConstants.STRING);
            String name = (String) xpath.evaluate("name/text/@value", node, XPathConstants.STRING);

            contact.setSourceId(sourceId);
            contact.setName(name);
            contactList.add(contact);
        }

    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    return contactList;
}