Example usage for org.dom4j DocumentHelper parseText

List of usage examples for org.dom4j DocumentHelper parseText

Introduction

In this page you can find the example usage for org.dom4j DocumentHelper parseText.

Prototype

public static Document parseText(String text) throws DocumentException 

Source Link

Document

parseText parses the given text as an XML document and returns the newly created Document.

Usage

From source file:com.amalto.workbench.utils.XmlUtil.java

License:Open Source License

public static Document fromXml(String text) throws DocumentException {

    Document document = DocumentHelper.parseText(text);

    return document;
}

From source file:com.anite.zebra.ext.xmlloader.XMLLoadProcess.java

License:Apache License

/**
 * Read in a file of XML, strip out the pretty printing via some juggling of objects and then return a
 * org.w3.document DOM object.//from w  w w  .j  a  v a  2s . c om
 * 
 * @param xmlFile
 *            The file to be read in.
 * @return A ready to use org.w3.Document with pretty printing stripped out.
 * @throws DocumentException
 * @throws MalformedURLException
 * @throws UnsupportedEncodingException
 * @throws IOException
 */
private Document readDocument(File xmlFile)
        throws DocumentException, MalformedURLException, UnsupportedEncodingException, IOException {
    SAXReader xmlReader = new SAXReader();
    xmlReader.setStripWhitespaceText(true);

    org.dom4j.Document dom4jDocument = xmlReader.read(xmlFile);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OutputFormat format = OutputFormat.createCompactFormat();
    XMLWriter writer = new XMLWriter(baos, format);

    writer.write(dom4jDocument);

    dom4jDocument = DocumentHelper.parseText(baos.toString());

    DOMWriter domWriter = new DOMWriter();
    Document doc = domWriter.write(dom4jDocument);
    return doc;
}

From source file:com.atguigu.p2p.util.XmlUtils.java

License:Apache License

@SuppressWarnings("unchecked")
public static Map<String, String> xml2Map(String xml) {
    Map<String, String> map = new HashMap<String, String>();
    try {/*from  w  w  w  .ja v a2s.c  o m*/
        Document document = DocumentHelper.parseText(xml);
        Element rootElement = document.getRootElement();
        for (Iterator<Element> it = rootElement.elementIterator(); it.hasNext();) {
            Element element = (Element) it.next();
            map.put(element.getName(), element.getText());
        }
    } catch (Exception e) {
        logger.error("xml2Map error:", e);
    }
    return map;
}

From source file:com.atguigu.p2p.util.XmlUtils.java

License:Apache License

@SuppressWarnings("unchecked")
public static List<Map<String, String>> xml2MapList(String xml, String xPath) {
    List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
    try {/*from w ww .ja  v a  2 s  . co  m*/
        Document document = DocumentHelper.parseText(xml);
        List<Element> selectNodes = document.selectNodes(xPath);
        for (Element e : selectNodes) {
            Map<String, String> map = new HashMap<String, String>();
            for (Iterator<Element> it = e.elementIterator(); it.hasNext();) {
                Element element = (Element) it.next();
                map.put(element.getName(), element.getText());
            }
            mapList.add(map);
        }
    } catch (Exception e) {
        logger.error("xml2MapList error:", e);
    }
    return mapList;
}

From source file:com.baidu.terminator.plugin.extractor.http.HttpXmlExtractor.java

License:Open Source License

@Override
public List<RequestElement> extract(Object request) {
    List<RequestElement> elements = new ArrayList<RequestElement>();
    HttpRequest httpRequest = (HttpRequest) request;
    String method = httpRequest.getMethod().getName();
    RequestElement methondElement = new RequestElement();
    methondElement.setKey("METHOD");
    methondElement.setValue(method);/*from   w  w  w. j  av  a2  s.  c  om*/
    elements.add(methondElement);

    String uri = httpRequest.getUri();
    List<RequestElement> uri_elements = UriElementGetter.getUri(uri);
    for (int i = 0; i < uri_elements.size(); i++) {
        elements.add(uri_elements.get(i));
    }
    //      RequestElement uriElement = new RequestElement();
    //      uriElement.setKey("URI");
    //      uriElement.setValue(uri);
    //      elements.add(uriElement);

    List<Entry<String, String>> headers = httpRequest.getHeaders();
    for (Entry<String, String> entry : headers) {
        RequestElement headerElement = new RequestElement();
        headerElement.setKey(entry.getKey());
        headerElement.setValue(entry.getValue());
        elements.add(headerElement);
    }

    ChannelBuffer content = httpRequest.getContent();
    if (content.readable()) {
        String stringContent = ChannelUtil.readChannelBufferAsString(content);
        Document document = null;
        try {
            document = DocumentHelper.parseText(stringContent);
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Element root = document.getRootElement();
        contentmap.clear();
        getElementList(root);
        for (int i = 0; i < contentmap.size(); i++) {
            elements.add((RequestElement) contentmap.get(i));
        }
    }
    logger.info("the elements of request is :" + elements);
    return elements;
}

From source file:com.beyondb.geocoding.BaiduAPI.java

public static String getPointByAddress(String address, String city) throws IOException {
    String resultPoint = "";
    try {/*w w  w .  j  av  a 2 s .c om*/
        URL url = new URL("http://api.map.baidu.com/geocoder/v2/?ak=" + ak + "&output=xml&address=" + address
                + "&" + city);

        URLConnection connection = url.openConnection();
        /**
         * ??URLConnection?Web
         * URLConnection???Web???
         */
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
        //        remember to clean up
        out.flush();
        out.close();
        //        ?????

        String res;
        InputStream l_urlStream;
        l_urlStream = connection.getInputStream();
        if (l_urlStream != null) {
            BufferedReader in = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8"));
            StringBuilder sb = new StringBuilder("");
            while ((res = in.readLine()) != null) {
                sb.append(res.trim());
            }
            String str = sb.toString();
            System.out.println(str);
            Document doc = DocumentHelper.parseText(str); // XML
            Element rootElt = doc.getRootElement(); // ?
            //            System.out.println("" + rootElt.getName()); // ??
            Element resultElem = rootElt.element("result");
            if (resultElem.hasContent()) {
                Element locationElem = resultElem.element("location");
                Element latElem = locationElem.element("lat");
                //            System.out.print("lat:"+latElem.getTextTrim()+",");
                Element lngElem = locationElem.element("lng");
                //            System.out.println("lng:"+lngElem.getTextTrim());
                resultPoint = lngElem.getTextTrim() + "," + latElem.getTextTrim();
            } else {
                System.out.println("can't compute the coor");
                resultPoint = " , ";
            }
        } else {
            resultPoint = " , ";
        }

    } catch (DocumentException ex) {
        Logger.getLogger(BaiduAPI.class.getName()).log(Level.SEVERE, null, ex);
    }
    return resultPoint;
}

From source file:com.beyondb.geocoding.SkyMapAPI.java

/**
* ??????//  w w w .ja  va2s . c o  m
*???????
* @param address
* @param city
* @return
*/
public Map<String, Coordinate> getPlaces(String address, String city) {
    Map<String, Coordinate> map = null;
    try {

        URL url = new URL(requestURL);//webService?XML?
        String soapRequest = getRequestXML(
                city == null || city.isEmpty() ? ("" + address) : (city + " " + address));

        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
        con.setRequestProperty("Content-Length", String.valueOf(soapRequest.length()));
        con.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
        // con.setRequestProperty("SOAPAction",_soap_action_str);

        con.setDoOutput(true);
        con.setConnectTimeout(3000);//3?,??ip???socket??????

        con.setRequestMethod("POST");
        con.setUseCaches(false);//post?

        OutputStream out = con.getOutputStream();

        out.write(soapRequest.getBytes());
        out.flush();
        out.close();
        int code = 0;

        StringBuilder content = new StringBuilder();
        code = con.getResponseCode(); //?????
        BufferedReader br;
        String line = "";
        if (code == HttpURLConnection.HTTP_OK) {

            br = new BufferedReader(new InputStreamReader(con.getInputStream()));

            while ((line = br.readLine()) != null) {
                content.append(line);

            }
            //? XML??
            //            <?xml version="1.0" encoding="UTF-8"?><wfs:FeatureCollection xmlns:topp="http://www.openplans.org/topp" xmlns:wfs="http://www.opengis.net/wfs" xmlns:ogc="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/WFS-basic.xsd" service="WFS" outputFormat="gml" version="1.0">
            //<gml:featureMember xmlns:iso19112="SI_Gazetteer"><iso19112:SI_Gazetteer><Geometry><gml:Point srsName="-1"><gml:coordinates>116.394272,39.900472</gml:coordinates></gml:Point></Geometry><ogc:id>1003716709</ogc:id><ogc:name></ogc:name><ogc:tel>010-65243322</ogc:tel><ogc:addnamel>44?</ogc:addnamel><ogc:admin>156110101</ogc:admin><ogc:cls>100102 100100 100000</ogc:cls><ogc:level/><ogc:zip/></iso19112:SI_Gazetteer></gml:featureMember>
            //<gml:featureMember xmlns:iso19112="SI_Gazetteer"><iso19112:SI_Gazetteer><Geometry><gml:Point srsName="-1"><gml:coordinates>116.394504,39.9013</gml:coordinates></gml:Point></Geometry><ogc:id>1003546134</ogc:id><ogc:name></ogc:name><ogc:tel>010-65241304</ogc:tel><ogc:addnamel>37?</ogc:addnamel><ogc:admin>156110101</ogc:admin><ogc:cls>100501 100500 100000 100105 100100 100000</ogc:cls><ogc:level/><ogc:zip/></iso19112:SI_Gazetteer></gml:featureMember>
            //<gml:featureMember xmlns:iso19112="SI_Gazetteer"><iso19112:SI_Gazetteer><Geometry><gml:Point srsName="-1"><gml:coordinates>116.393824,39.900068</gml:coordinates></gml:Point></Geometry><ogc:id>1025053239</ogc:id><ogc:name>?</ogc:name><ogc:tel>010-65122265</ogc:tel><ogc:addnamel>44?</ogc:addnamel><ogc:admin>156110101</ogc:admin><ogc:cls>010100 010000</ogc:cls><ogc:level/><ogc:zip/></iso19112:SI_Gazetteer></gml:featureMember>
            //<gml:featureMember xmlns:iso19112="SI_Gazetteer"><iso19112:SI_Gazetteer><Geometry><gml:Point srsName="-1"><gml:coordinates>116.3938,39.899528</gml:coordinates></gml:Point></Geometry><ogc:id>1003552834</ogc:id><ogc:name>?</ogc:name><ogc:tel>010-65241042</ogc:tel><ogc:addnamel>44?</ogc:addnamel><ogc:admin>156110101</ogc:admin><ogc:cls>010116 010100 010000</ogc:cls><ogc:level/><ogc:zip/></iso19112:SI_Gazetteer></gml:featureMember>
            //   <gml:featureMember xmlns:iso19112="SI_Gazetteer">
            //            <iso19112:SI_Gazetteer>
            //               <Geometry>
            //                  <gml:Point srsName="-1">
            //                     <gml:coordinates>116.3938,39.899532</gml:coordinates>
            //                  </gml:Point>
            //               </Geometry>
            //               <ogc:id>1021636362</ogc:id>
            //               <ogc:name>?</ogc:name>
            //               <ogc:tel>010-65241042</ogc:tel>
            //               <ogc:addnamel>44?</ogc:addnamel>
            //               <ogc:admin>156110101</ogc:admin>
            //               <ogc:cls>010116 010100 010000</ogc:cls>
            //               <ogc:level/>
            //               <ogc:zip/>
            //            </iso19112:SI_Gazetteer>
            //   </gml:featureMember>
            //</wfs:FeatureCollection>
            Document doc = DocumentHelper.parseText(content.toString()); // XML
            Element rootElt = doc.getRootElement(); // ?FeatureCollection

            for (Iterator it = rootElt.elementIterator("featureMember"); it.hasNext();) {
                if (map == null) {
                    map = new HashMap<>();
                }
                Element featureMemberElement = (Element) it.next();
                Element gazetterEle = featureMemberElement.element("SI_Gazetteer");
                Element geoEle = gazetterEle.element("Geometry");
                Element pointEle = geoEle.element("Point");
                Element coordEle = pointEle.element("coordinates");
                String[] coordinate = coordEle.getTextTrim().split(",");
                Coordinate tmpCoordinate = new Coordinate();
                tmpCoordinate.Longitude = Double.parseDouble(coordinate[0]);
                tmpCoordinate.Latitude = Double.parseDouble(coordinate[1]);
                Element nameEle = gazetterEle.element("name");
                map.put(nameEle.getTextTrim(), tmpCoordinate);
            }

        } else {
            //?HTTP??HTTP_OK??
            InputStream is = con.getErrorStream(); //getErrorStreamXML??JDOM??
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            br = new BufferedReader(isr);
            while ((line = br.readLine()) != null) {
                content.append(line);
            }
            Logger.getLogger(SkyMapAPI.class.getName()).log(Level.SEVERE, "??");
        }

    } catch (MalformedURLException e) {
        Logger.getLogger(SkyMapAPI.class.getName()).log(Level.SEVERE, null, e);
    } catch (IOException | DocumentException e) {
        Logger.getLogger(SkyMapAPI.class.getName()).log(Level.SEVERE, null, e);
    }
    return map;
}

From source file:com.bizideal.whoami.utils.cloopen.CCPRestSmsSDK.java

License:Open Source License

/**
 * @description xml??map//from   ww  w. j a  v  a 2  s  . co  m
 * @param xml
 * @return Map
 */
private HashMap<String, Object> xmlToMap(String xml) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    Document doc = null;
    try {
        doc = DocumentHelper.parseText(xml); // XML
        Element rootElt = doc.getRootElement(); // ?
        HashMap<String, Object> hashMap2 = new HashMap<String, Object>();
        for (Iterator i = rootElt.elementIterator(); i.hasNext();) {
            Element e = (Element) i.next();
            if ("statusCode".equals(e.getName()) || "statusMsg".equals(e.getName()))
                map.put(e.getName(), e.getText());
            else {
                if ("SubAccount".equals(e.getName()) || "totalCount".equals(e.getName())
                        || "token".equals(e.getName()) || "downUrl".equals(e.getName())) {
                    if (!"SubAccount".equals(e.getName())) {
                        hashMap2.put(e.getName(), e.getText());
                    } else {
                        ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>();
                        HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                        for (Iterator i2 = e.elementIterator(); i2.hasNext();) {
                            Element e2 = (Element) i2.next();
                            hashMap3.put(e2.getName(), e2.getText());
                            arrayList.add(hashMap3);
                        }
                        hashMap2.put("SubAccount", arrayList);
                    }
                    map.put("data", hashMap2);
                } else {

                    HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                    for (Iterator i2 = e.elementIterator(); i2.hasNext();) {
                        Element e2 = (Element) i2.next();
                        // hashMap2.put(e2.getName(),e2.getText());
                        hashMap3.put(e2.getName(), e2.getText());
                    }
                    if (hashMap3.size() != 0) {
                        hashMap2.put(e.getName(), hashMap3);
                    } else {
                        hashMap2.put(e.getName(), e.getText());
                    }
                    map.put("data", hashMap2);
                }
            }
        }
    } catch (DocumentException e) {
        e.printStackTrace();
        LoggerUtil.error(e.getMessage());
    } catch (Exception e) {
        LoggerUtil.error(e.getMessage());
        e.printStackTrace();
    }
    return map;
}

From source file:com.blocks.framework.utils.date.XMLDom4jUtils.java

License:Open Source License

/**
 * Create dom4j document from xmlSource//w  ww .  jav  a  2 s . co m
 *
 * @param xmlSource
 *            URL?XML?XML?? Object
 * @param validate
 *            boolean
 * @param encoding
 *            String
 * @throws DocumentException
 * @throws IOException
 * @return Document
 * @throws BaseException
 */
public static Document createDocument(Object xmlSource, boolean validate, String encoding)
        throws BaseException {

    // Use xerces and validate XML file
    if (xmlSource instanceof Document)
        return (Document) xmlSource;
    Document doc = null;
    SAXReader saxReader = new SAXReader(true);
    saxReader.setValidation(validate);
    if (encoding == null || encoding.equals("")) {
        encoding = DEFAULT_ENCODING;
    }

    // Check input source type
    if (xmlSource instanceof StringBuffer)
        xmlSource = ((StringBuffer) xmlSource).toString();

    try {
        if (xmlSource instanceof String) {
            if (((String) xmlSource).startsWith("<")) {
                // Treat the String as XML code
                StringReader reader = new StringReader(xmlSource.toString());
                DocumentHelper.parseText(xmlSource.toString());
                doc = saxReader.read(reader, encoding);
            } else {
                doc = saxReader.read(new File((String) xmlSource));
            }
        } else if (xmlSource instanceof File) {
            doc = saxReader.read((File) xmlSource);
        } else if (xmlSource instanceof InputStream) {
            doc = saxReader.read((InputStream) xmlSource);
        } else if (xmlSource instanceof Reader) {
            doc = saxReader.read((Reader) xmlSource);
        } else if (xmlSource instanceof URL) {
            doc = saxReader.read((URL) xmlSource);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new BaseException("UTIL-0001", ex);
    }

    return doc;
}

From source file:com.brick.util.nciic.NciicUtil.java

/**
 * ?XML/*w  w w  . j a  v  a 2 s  .c  o m*/
 * @param text
 * @return
 * @throws Exception
 */
public static List<NciicEntity> readResult(String text) throws Exception {
    List<NciicEntity> resultList = new ArrayList<NciicEntity>();
    NciicEntity result = null;
    Document d;
    XMLWriter writer = null;
    try {
        //SAXReader reader = new SAXReader();
        //d = reader.read(new File("d:/test/testxml.xml"));
        d = DocumentHelper.parseText(text);
        String dateStr = DateUtil.dateToString(new Date(), "[yyyy-MM-dd][HH-mm]");
        File xmlPath = new File(XML_PATH);
        if (!xmlPath.exists()) {
            xmlPath.mkdirs();
        }
        File xpPath = new File(XP_PATH);
        if (!xpPath.exists()) {
            xpPath.mkdirs();
        }
        writer = new XMLWriter(new FileOutputStream(new File(xmlPath, dateStr + ".xml")));
        writer.write(d);
        writer.flush();
        writer.close();
        writer = null;

        Element root = d.getRootElement();
        List<Element> allResult = root.elements("ROW");
        Element input = null;
        List<Element> output = null;
        String result_msg = null;
        for (Element element : allResult) {
            result = new NciicEntity();
            result_msg = null;
            input = element.element("INPUT");
            result.setGmsfhm(input.element("gmsfhm").getText());
            result.setXm(input.element("xm").getText());
            output = element.element("OUTPUT").elements("ITEM");
            for (Element out_element : output) {
                if (out_element.element("result_gmsfhm") != null) {
                    result.setResult_gmsfhm(out_element.element("result_gmsfhm").getText());
                }
                if (out_element.element("result_xm") != null) {
                    result.setResult_xm(out_element.element("result_xm").getText());
                }
                if (out_element.element("errormesage") != null) {
                    result.setError_msg(out_element.element("errormesage").getText());
                }
                if (out_element.element("errormesagecol") != null) {
                    result.setError_msg_col(out_element.element("errormesagecol").getText());
                }
                if (out_element.element("xp") != null) {
                    result.setXp(out_element.element("xp").getText());
                }
                if (!StringUtils.isEmpty(result.getXp())) {
                    try {
                        File f = new File(xpPath, result.getGmsfhm() + "-" + result.getXm() + ".jpg");
                        BufferedImage img = ImageIO.read(
                                new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(result.getXp())));
                        ImageIO.write(img, "jpg", f);
                        result.setXp_file(f.getPath());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            if ("".equals(result.getResult_gmsfhm()) && "".equals(result.getResult_xm())) {
                result_msg = "";
            } else {
                if ("?".equals(result.getResult_gmsfhm())) {
                    result_msg = "???";
                } else if ("?".equals(result.getResult_xm())) {
                    result_msg = "???";
                } else if (!StringUtils.isEmpty(result.getError_msg())) {
                    result_msg = result.getError_msg();
                    if (!StringUtils.isEmpty(result.getError_msg_col())) {
                        result_msg += "(" + result.getError_msg_col() + ")";
                    }
                }
            }
            result.setResult_msg(result_msg);
            resultList.add(result);
        }
        return resultList;
    } catch (Exception e) {
        throw e;
    } finally {
        if (writer != null) {
            writer.flush();
            writer.close();
            writer = null;
        }
    }
}