Example usage for org.dom4j Node getText

List of usage examples for org.dom4j Node getText

Introduction

In this page you can find the example usage for org.dom4j Node getText.

Prototype

String getText();

Source Link

Document

Returns the text of this node.

Usage

From source file:com.controlj.addon.weather.noaa.StationSourceFactory.java

License:Open Source License

private String findClosestWeatherStationID(Document weatherStations, float latitude, float longitude) {
    XPath idXpath = weatherStations.createXPath("station_id");
    float minDistance = Float.MAX_VALUE;
    String minId = null;// ww w.  j  ava2  s  .  c o m

    List stations = weatherStations.selectNodes("/wx_station_index//station");
    for (Object station : stations) {
        try {
            StationSourceImpl stationSource = new StationSourceImpl((Node) station);
            float nextDistance = stationSource.getDistanceTo(latitude, longitude, false);
            if (nextDistance < minDistance) {
                Node id = idXpath.selectSingleNode(station);
                if (id != null) {
                    minId = id.getText();
                    minDistance = nextDistance;
                }
            }
        } catch (NumberFormatException e) {
        } // skip this one if malformed
    }
    return minId;
}

From source file:com.controlj.addon.weather.noaa.StationSourceImpl.java

License:Open Source License

private Float getFloatValue(XPath xpath) {
    Float result = null;//from  www . j a  v a2 s.c  om
    Node node = xpath.selectSingleNode(stationNode);
    if (node != null) {
        try {
            result = new Float(node.getText());
        } catch (NumberFormatException e) {
        } // ignore and return null
    }
    return result;
}

From source file:com.controlj.addon.weather.noaa.StationSourceImpl.java

License:Open Source License

private String getStringValue(XPath xpath) {
    String result = null;/*from  w  ww  . j  a v a 2s  . co m*/
    Node node = xpath.selectSingleNode(stationNode);
    if (node != null) {
        result = node.getText();
    }
    return result;
}

From source file:com.controlj.addon.weather.wbug.service.WeatherBugDataUtils.java

License:Open Source License

private static void extractError(Document doc) throws WeatherBugServiceException {
    Node h1 = doc.getRootElement().selectSingleNode("/h1");
    if (h1 != null)
        throw new WeatherBugServiceException(h1.getText());

    Node title = doc.getRootElement().selectSingleNode("/rss/channel/title");
    if (title != null && "Observations from ,  - USA".equals(title.getText()))
        throw new WeatherBugServiceException("Missing station content");

    Logging.logDocument("unknown", "Unknown error", doc);
    throw new WeatherBugServiceException("Unknown error");
}

From source file:com.cy.dcts.identityVerify.service.impl.IdentityVerifyServiceImpl.java

private Map<String, String> paresXml2Map(String xml) {
    Map<String, String> map = new HashMap<String, String>();
    Document document = null;/*from   w w w.j  a va2 s  .  c o  m*/
    String errormesage = "";
    String errormesagecol = "";
    String idNumberRst = "";
    String xmRst = "";
    String errorMsg = "";
    String errorCode = "";
    try {
        document = DocumentHelper.parseText(xml);
        Element rootElement = document.getRootElement();//?

        Attribute rootAttr = rootElement.attribute("errorcode");
        if (rootAttr != null) {
            Node errorCodeNode = rootElement.selectSingleNode("//RESPONSE/ROWS/ROW/ErrorCode");
            Node errorMsgNode = rootElement.selectSingleNode("//RESPONSE/ROWS/ROW/ErrorMsg");
            if (errorCodeNode != null && errorMsgNode != null) {
                errorMsg = errorMsgNode.getText();
                errorCode = errorCodeNode.getText();
            }
            map.put("errorCode", errorCode);
            map.put("errorMsg", errorMsg);
            return map;
        }

        Node idNumberNode = rootElement.selectSingleNode("//ROWS/ROW/INPUT/gmsfhm");
        String idNumber = idNumberNode.getText();
        String name = rootElement.selectSingleNode("//ROWS/ROW/INPUT/xm").getText();
        map.put("gmsfhm", idNumber);
        map.put("xm", name);

        Node sfNode = rootElement.selectSingleNode("//ROWS/ROW/OUTPUT/ITEM/result_gmsfhm");
        Node xmNode = rootElement.selectSingleNode("//ROWS/ROW/OUTPUT/ITEM/result_xm");
        if (sfNode == null || xmNode == null) {
            Node errorMsgNode = rootElement.selectSingleNode("//ROWS/ROW/OUTPUT/ITEM/errormesage");
            Node errorColNode = rootElement.selectSingleNode("//ROWS/ROW/OUTPUT/ITEM/errormesagecol");
            if (errorMsgNode != null && errorColNode != null) {
                errormesage = errorMsgNode.getText();
                errormesagecol = errorColNode.getText();
            }
        } else {
            idNumberRst = sfNode.getText();
            xmRst = xmNode.getText();
        }

        map.put("result_gmsfhm", idNumberRst);
        map.put("result_xm", xmRst);
        map.put("errormesage", errormesage);
        map.put("errormesagecol", errormesagecol);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    return map;
}

From source file:com.devoteam.srit.xmlloader.core.Parameter.java

License:Open Source License

public void applyXPath(String xml, String xpath, boolean deleteNS) throws Exception {
    // remove beginning to '<' character
    int iPosBegin = xml.indexOf('<');
    if (iPosBegin > 0) {
        xml = xml.substring(iPosBegin);//ww w  . j  a va 2s .c  om
    }
    // remove from '>' character to the end
    int iPosEnd = xml.lastIndexOf('>');
    if ((iPosEnd > 0) && (iPosEnd < xml.length() - 1)) {
        xml = xml.substring(0, iPosEnd + 1);
    }

    int iPosXMLLine = xml.indexOf("<?xml");
    if (iPosXMLLine < 0) {
        xml = "<?xml version='1.0'?>" + xml;
    }

    // remove the namespace because the parser does not support them if there are not declare in the root node
    if (deleteNS) {
        xml = xml.replaceAll("<[a-zA-Z\\.0-9_]+:", "<");
        xml = xml.replaceAll("</[a-zA-Z\\.0-9_]+:", "</");
    }
    // remove doctype information (dtd files for the XML syntax)
    xml = xml.replaceAll("<!DOCTYPE\\s+\\w+\\s+\\w+\\s+[^>]+>", "");

    InputStream input = new ByteArrayInputStream(xml.getBytes());
    SAXReader reader = new SAXReader(false);
    reader.setEntityResolver(new XMLLoaderEntityResolver());
    Document document = reader.read(input);

    XPath xpathObject = document.createXPath(xpath);
    Object obj = xpathObject.evaluate(document.getRootElement());

    if (obj instanceof List) {
        List<Node> list = (List<Node>) obj;
        for (Node node : list) {
            add(node.asXML());
        }
    } else if (obj instanceof DefaultElement) {
        Node node = (Node) obj;
        add(node.asXML());
    } else if (obj instanceof DefaultAttribute) {
        Node node = (Node) obj;
        add(node.getStringValue());
    } else if (obj instanceof DefaultText) {
        Node node = (Node) obj;
        add(node.getText());
    } else {
        add(obj.toString());
    }
}

From source file:com.devoteam.srit.xmlloader.core.utils.XMLElementTextOnlyParser.java

License:Open Source License

public List<Element> replace(Element element, ParameterPool variables) throws Exception {
    List<Element> result = new LinkedList();
    result.add(element.createCopy());//from  w w w .jav a  2s . c  o m
    element = result.get(0);

    Iterator nodesIterator = element.nodeIterator();
    HashMap<Node, Node> nodesToReplace = new HashMap<Node, Node>();

    boolean alreadyNext = false;

    while (nodesIterator.hasNext()) {
        Node node = null;
        if (!alreadyNext) {
            node = (Node) nodesIterator.next();
        }

        Node lastTextNode = null;
        String lastTextNodeText = "";
        alreadyNext = false;

        //
        // We put all successive TEXT Nodes into one node ( there is some fragmentation i don't understand )
        //
        while (null != node && node.getNodeType() == Node.TEXT_NODE) {
            alreadyNext = true;
            lastTextNode = (Text) node;
            lastTextNodeText += lastTextNode.getText();

            // this node will be deleted later ... if not overwritten in this hashmap
            nodesToReplace.put(lastTextNode, null);
            if (nodesIterator.hasNext()) {
                node = (Node) nodesIterator.next();
            } else {
                node = null;
            }
        }

        //
        // We process normally the CDATA Nodes
        // 
        if (null != node && node.getNodeType() == Node.CDATA_SECTION_NODE) {
            lastTextNode = (Node) node;
            lastTextNodeText = lastTextNode.getText();
        }

        //
        // We do nothing for the other type Nodes
        // 
        if (null == lastTextNode) {
            continue;
        }

        lastTextNode.setText(lastTextNodeText);

        //
        // Now that we have only one, complete, TEXT node or one CDATA node to proceed
        //
        Node textNode = (Node) lastTextNode;

        String text = textNode.getText();
        String out = "";

        int endOfLine;
        String line;

        //
        // Transform all \r\n, in \n
        //
        //text = Utils.replaceNoRegex(text, "\r", "");

        while (text.length() > 0) {
            //
            // Read a line
            //
            endOfLine = text.indexOf("\n");

            if (endOfLine == -1) {
                line = text;
                text = "";
            } else {
                line = text.substring(0, endOfLine + 1);
                text = text.substring(endOfLine + 1);
            }

            //
            // Replace line if it contains at least a variable
            //
            if (Parameter.containsParameter(line)) {
                List<String> results = variables.parse(line);

                for (String s : results) {
                    out += s;
                }
            } else {
                out += line;
            }
        }

        //
        // Set new text into new AVP
        //
        Text newTextNode = new DefaultText(out);
        nodesToReplace.put(textNode, newTextNode);
    }

    for (Node key : nodesToReplace.keySet()) {
        DefaultElementInterface.replaceNode((DefaultElement) element, key, nodesToReplace.get(key));
    }

    if (result.size() != 1) {
        throw new ExecutionException("Size of result for XMLElementTextOnlyParser should be 1");
    }

    return result;
}

From source file:com.devoteam.srit.xmlloader.genscript.Param.java

License:Open Source License

public String applySubstitution(String text, Msg msg) throws Exception {

    String msgAvecParametres = "";

    if (getRegle() != null) {
        String[] regexTab = getRegle().split("#");

        // Si la regle est sous forme d'expression rgulire
        if (regexTab[0].toUpperCase().contains("REGEX")) {
            GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.CORE,
                    "Replace parameter " + getRegle() + " => " + name);
            String[] regexRule = Arrays.copyOfRange(regexTab, 1, regexTab.length);
            msgAvecParametres = regexRemplace(regexRule, 0, text);
        }/* w ww  .java 2 s .  c o m*/
        // Si la regle est sous forme de xpath
        else if (regexTab[0].toUpperCase().contains("XPATH")) {
            GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.CORE,
                    "Replace parameter " + getRegle() + " => " + name);
            // Rcupration des paramtres
            String xpathRule = regexTab[1];
            String attribut = regexTab[2];

            attribut = attribut.replace("@", "");

            // Cration de l'arbre DOM correspondant au message
            SAXReader reader = new SAXReader();
            try {
                Document document = reader.read(new ByteArrayInputStream(text.getBytes("UTF-8")));
                // Cration de l'objet XPATH ) selectionner 
                XPath xpath = new DefaultXPath(xpathRule);

                // Rcupration des noeuds correspondants
                List<Node> nodes = xpath.selectNodes(document.getRootElement(), xpath);

                // Pour chaque noeuds  modifier
                Element aRemplacer = null;
                for (Node n : nodes) {
                    setRemplacedValue(n.getText());
                    if (n instanceof Element) {
                        aRemplacer = (Element) n;
                    } else {
                        aRemplacer = n.getParent();
                    }
                    String newValue = getName();
                    String oldValue = aRemplacer.attribute(attribut).getValue();
                    // On regarde si on est dans le cas de paramtres mixtes
                    if (regexTab.length > 3) {
                        if (regexTab[3].equals("REGEX")) {
                            setRemplacedValue(null);
                            String[] regexRule = Arrays.copyOfRange(regexTab, 4, regexTab.length);
                            newValue = regexRemplace(regexRule, 0, oldValue);
                        }
                    }
                    aRemplacer.setAttributeValue(attribut, newValue);
                }

                // Convertion en chane de caractre de l'arbre DOM du message
                msgAvecParametres = document.getRootElement().asXML();
            } catch (Exception e) {

            }
        }
        // si la rgle est sous forme de pathkey
        else if (regexTab[0].toUpperCase().contains("PATHKEY")) {

            String valeurARemplacer = null;
            // On rcupre la valeur  remplacer
            String pathKeyWord = regexTab[1];
            if (msg != null) {
                Parameter valeurParamARemplacer = msg.getParameter(pathKeyWord);
                if (valeurParamARemplacer.length() > 0) {
                    valeurARemplacer = valeurParamARemplacer.get(0).toString();
                }

                // On remplace dans tout le message par le parametre
                if (valeurARemplacer != null) {
                    msgAvecParametres = text.replace(valeurARemplacer, getName());
                    if (!msgAvecParametres.equals(text)) {
                        GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.CORE,
                                "Replace parameter " + valeurARemplacer + " => " + name);
                        setRemplacedValue(valeurARemplacer);
                    }
                }
            }
        }
    }
    // Si le message n'a pas subit de modification, on retourne null
    if (!isUsed()) {
        return null;
    }

    // Sinon on retourne le message modifi avec les paramtres
    return msgAvecParametres;
}

From source file:com.dotmarketing.viewtools.XmlTool.java

License:Apache License

/**
 * Returns the concatenated text content of all the internally held nodes. Obviously, this is most useful when only
 * one node is held.// ww  w .ja va2 s .co m
 */
public String getText() {
    if (isEmpty()) {
        return null;
    }
    StringBuilder out = new StringBuilder();
    for (Node n : nodes) {
        String text = n.getText();
        if (text != null) {
            out.append(text);
        }
    }
    String result = out.toString().trim();
    if (result.length() > 0) {
        return result;
    }
    return null;
}

From source file:com.dotmarketing.viewtools.XmlTool.java

License:Apache License

/**
 * If this instance has no XML {@link Node}s, then this returns the result of {@code super.toString()}. Otherwise,
 * it returns the XML (as a string) of all the internally held nodes that are not {@link Attribute}s. For
 * attributes, only the value is used./*from   w w  w.  j  ava2 s. c o m*/
 */
public String toString() {
    if (isEmpty()) {
        return super.toString();
    }
    StringBuilder out = new StringBuilder();
    for (Node n : nodes) {
        if (n instanceof Attribute) {
            out.append(n.getText().trim());
        } else {
            out.append(n.asXML());
        }
    }
    return out.toString();
}