Example usage for org.dom4j Document getRootElement

List of usage examples for org.dom4j Document getRootElement

Introduction

In this page you can find the example usage for org.dom4j Document getRootElement.

Prototype

Element getRootElement();

Source Link

Document

Returns the root Element for this document.

Usage

From source file:com.glaf.wechat.util.MessageUtils.java

License:Apache License

/**
 * ???XML//from   w w  w  . j a va2  s  . c o m
 * 
 * @param request
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public static Map<String, String> parseXml(HttpServletRequest request) {
    // ?HashMap
    Map<String, String> map = new java.util.concurrent.ConcurrentHashMap<String, String>();

    // request??
    InputStream inputStream = null;
    // ??
    SAXReader reader = new SAXReader();
    try {
        inputStream = request.getInputStream();

        Document document = reader.read(inputStream);
        // xml
        Element root = document.getRootElement();
        // ?
        List<Element> elementList = root.elements();

        // ???
        for (Element e : elementList) {
            map.put(e.getName(), e.getText());
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        try {
            // ?
            if (inputStream != null) {
                inputStream.close();
                inputStream = null;
            }
        } catch (IOException ex) {
        }
    }

    return map;
}

From source file:com.globalsight.cxe.adapter.msoffice.ExcelRepairer.java

License:Apache License

private void repairWt() throws Exception {
    List<File> fs = getExcelRepairFiles();

    for (File f : fs) {
        String content = FileUtil.readFile(f, "utf-8");

        XmlParser parser = new XmlParser();
        org.dom4j.Document document = parser.parseXml(content);
        Element element = document.getRootElement();

        @SuppressWarnings("unchecked")
        List<Element> wts = element.selectNodes("//t");

        for (Element wt : wts) {
            if (wt == null)
                continue;

            @SuppressWarnings("unchecked")
            List<Element> es = wt.elements();
            if (!wt.isTextOnly()) {
                String text = wt.getStringValue();
                for (Element e : es) {
                    wt.remove(e);//from w  w  w .  j  ava2  s. co  m
                }

                wt.setText(text);
            }
        }

        Writer fileWriter = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
        XMLWriter xmlWriter = new XMLWriter(fileWriter);
        xmlWriter.write(document);
        xmlWriter.close();
    }
}

From source file:com.globalsight.cxe.adapter.msoffice.ExcelRepairer.java

License:Apache License

private void repairExcelSharedStrings() throws Exception {
    File f = new File(path + "/xl/sharedStrings.xml");
    if (!f.exists())
        return;/*from   www. j a v  a  2 s . com*/

    String content = FileUtil.readFile(f, "utf-8");

    XmlParser parser = new XmlParser();
    org.dom4j.Document document = parser.parseXml(content);
    Element element = document.getRootElement();
    List<Element> rs = getElementByName(element, "r");
    for (Element r : rs) {
        @SuppressWarnings("rawtypes")
        List els = r.content();

        StringBuffer sb = new StringBuffer();
        Element wt = null;
        List<DefaultText> texts = new ArrayList<DefaultText>();

        for (Object el : els) {
            if (el instanceof DefaultText) {
                DefaultText text = (DefaultText) el;
                String s = text.getStringValue();
                if ("\n".equals(s))
                    continue;

                texts.add(text);
                sb.append(text.getStringValue());
            } else if (el instanceof Element) {
                Element elm = (Element) el;
                if ("t".equals(elm.getName())) {
                    wt = elm;
                    sb.append(elm.getStringValue());
                }
            }
        }

        if (wt == null) {
            wt = r.addElement("t");
            wt.addAttribute("xml:space", "preserve");
        }

        if (sb.length() == 0)
            sb.append(" ");

        wt.clearContent();
        wt.addText(sb.toString());

        for (DefaultText text : texts) {
            r.remove(text);
        }
    }

    Writer fileWriter = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
    XMLWriter xmlWriter = new XMLWriter(fileWriter);
    xmlWriter.write(document);
    xmlWriter.close();
}

From source file:com.globalsight.cxe.adapter.msoffice.WordRepairer.java

License:Apache License

private static void repairDocFiles(File f) throws Exception {
    if (!f.exists())
        return;//ww w.jav a 2  s. co m

    StyleUtil util = StyleFactory.getStyleUtil(StyleFactory.DOCX);
    util.updateBeforeExport(f.getAbsolutePath());

    String content = FileUtil.readFile(f, "utf-8");

    XmlParser parser = new XmlParser();
    parser.setErrorHandler(new ErrorHandler() {
        @Override
        public void warning(SAXParseException arg0) throws SAXException {
            // Do nothing.
        }

        @Override
        public void fatalError(SAXParseException arg0) throws SAXException {
            return;
        }

        @Override
        public void error(SAXParseException e) throws SAXException {
            String s = e.getMessage();
            if (s.matches("Attribute .*? was already specified for element[\\s\\S]*"))
                return;

            throw new SAXException("XML parse error at\n  line " + e.getLineNumber() + "\n  column "
                    + e.getColumnNumber() + "\n  Message:" + e.getMessage());
        }
    });

    org.dom4j.Document document = parser.parseXml(content);
    Element element = document.getRootElement();

    forHyperlinkInWr(element);
    forHyperlinkInWt(element);
    forWtNotInWr(element);
    forTextInWr(element);
    forWrInWr(element);
    forTextInWp(element);
    forNodesInWt(element);

    Writer fileWriter = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
    XMLWriter xmlWriter = new XMLWriter(fileWriter);
    xmlWriter.write(document);
    xmlWriter.close();

    if (content.contains("</mc:AlternateContent>")) {
        forAlternateContent(f);
    }
}

From source file:com.globalsight.cxe.adapter.serviceware.Importer.java

License:Apache License

/**
 * Makes a special ServiceWareXML that contains the fields
 * GlobalSight needs to localize/* w  w  w  .j  a v a2s . co m*/
 *
 * @param p_koXml knowledge object XML
 * @return Service Ware XML to localize
 * @exception Exception
 */
private String makeServiceWareXml(String p_sessionId, String p_koXml) throws Exception {
    //first get some data from the knowledge objxml
    XmlParser xmlp = XmlParser.hire();
    Document d = xmlp.parseXml(p_koXml);
    Element root = d.getRootElement();
    String koName = root.selectSingleNode("/GetKOsResponse/return/SessionKOs/KO/Name").getText();
    m_koName = koName;
    String koShortDesc = root.selectSingleNode("/GetKOsResponse/return/SessionKOs/KO/ShortDescription")
            .getText();
    StringBuffer swXml = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
    swXml.append("<serviceWareXml>\r\n");
    swXml.append("<knowledgeObj id=\"");
    swXml.append(m_koid);
    swXml.append("\">\r\n");
    swXml.append("<knowledgeObjName>");
    swXml.append(koName);
    swXml.append("</knowledgeObjName>\r\n");
    swXml.append("<knowledgeObjShortDesc>");
    swXml.append(koShortDesc);
    swXml.append("</knowledgeObjShortDesc>\r\n");
    List conceptIdListNodes = root.selectNodes("/GetKOsResponse/return/SessionKOs/KO/ConceptIDs");
    String conceptIdListOrig = ((Node) conceptIdListNodes.get(0)).getText();
    m_logger.debug("orig concept Id list: " + conceptIdListOrig);
    String conceptIdList = conceptIdListOrig.replaceAll(", ", ",");
    m_logger.debug("fixed concept Ids: " + conceptIdList);

    //get the XML for all concept Objs
    String conceptObjXml = ServiceWareAPI.getConceptObjectXml(p_sessionId, conceptIdList);
    XmlParser conceptXmlp = XmlParser.hire();
    Document conceptDoc = conceptXmlp.parseXml(conceptObjXml);
    Element conceptRoot = conceptDoc.getRootElement();
    List conceptNodes = conceptRoot.selectNodes("/GetConceptsResponse/return/SessionConcepts/Concept");
    m_logger.debug("There are " + conceptNodes.size() + " concept nodes.");
    for (int i = 0; i < conceptNodes.size(); i++) {
        Node conceptNode = (Node) conceptNodes.get(i);
        String conceptId = conceptNode.selectSingleNode("ConceptID").getText();
        String conceptName = conceptNode.selectSingleNode("Name").getText();
        String conceptShortDesc = conceptNode.selectSingleNode("ShortDescription").getText();
        swXml.append("<concept id=\"");
        swXml.append(conceptId);
        swXml.append("\">");
        swXml.append("<conceptName>");
        swXml.append(conceptName);
        swXml.append("</conceptName>\r\n");
        swXml.append("<conceptShortDesc>");
        swXml.append(conceptShortDesc);
        swXml.append("</conceptShortDesc>\r\n");
        swXml.append("</concept>\r\n");
    }
    swXml.append("</knowledgeObj>\r\n");
    swXml.append("</serviceWareXml>\r\n");
    XmlParser.fire(conceptXmlp);
    XmlParser.fire(xmlp);
    return swXml.toString();
}

From source file:com.globalsight.cxe.adapter.serviceware.ServiceWareAPI.java

License:Apache License

/**
 * Tries to connect to serviceware, and returns the sessionID.
 * // w  w  w .  j  a v  a2  s .  c  om
 * @return String
 * @exception Exception
 */
public static String connect() throws Exception {
    StringBuffer url = new StringBuffer(s_apiUrl);
    url.append("?Action=CreateSession&UserName=");
    url.append(s_username);
    url.append("&Password=");
    url.append(s_password);
    url.append("&KArea=");
    url.append(URLEncoder.encode(s_KArea));
    s_logger.debug("URL=" + url.toString());
    String xml = readXml(url.toString());
    s_logger.debug("XML is: " + xml);
    // now parse the XML to get the sessionId
    XmlParser xmlp = XmlParser.hire();
    Document d = xmlp.parseXml(xml);
    Element root = d.getRootElement();
    List nodes = root.selectNodes("/CreateSessionResponse/return/SessionID");
    Node node = (Node) nodes.get(0);
    String sessionId = node.getText();
    XmlParser.fire(xmlp);
    return sessionId;
}

From source file:com.globalsight.cxe.adapter.serviceware.ServiceWareAPI.java

License:Apache License

/**
 * Returns a Hashtable containing all the Knowledge Object Ids and their
 * names/* ww  w .  j  av  a 2 s.c  o  m*/
 * 
 * @param p_sessionId
 * @return
 * @exception Exception
 */
public static Hashtable getKnowledgeObjects(String p_sessionId) throws Exception {
    Hashtable ht = new Hashtable();
    StringBuffer url = new StringBuffer(s_apiUrl);
    url.append("?Action=GetKOs&SessionID=");
    url.append(p_sessionId);
    s_logger.debug("URL=" + url.toString());
    String xml = readXml(url.toString());
    s_logger.debug("XML is: " + xml);

    XmlParser xmlp = XmlParser.hire();
    Document d = xmlp.parseXml(xml);
    Element root = d.getRootElement();
    List idnodes = root.selectNodes("/GetKOsResponse/return/SessionKOs/KO/KOID");
    List namenodes = root.selectNodes("/GetKOsResponse/return/SessionKOs/KO/Name");
    for (int i = 0; i < idnodes.size(); i++) {
        Node id = (Node) idnodes.get(i);
        Node name = (Node) namenodes.get(i);
        s_logger.debug("Inserting: " + id.getText() + "," + name.getText());
        ht.put(id.getText(), name.getText());
    }
    XmlParser.fire(xmlp);
    return ht;
}

From source file:com.globalsight.cxe.adapter.serviceware.ServiceWareAPI.java

License:Apache License

/**
 * Takes in a serviceware xml and gets all IDs, names, and short
 * descriptions from it for updating ServiceWare
 * /* w  w w. j  a  v  a 2s  .c o  m*/
 * @param p_sessionId
 * @param p_serviceWareXml
 * @return
 */
public static void updateKnowledgeAndConceptObjects(String p_sessionId, String p_serviceWareXml,
        String p_targetLocale) throws Exception {
    XmlParser xmlp = XmlParser.hire();
    Document d = xmlp.parseXml(p_serviceWareXml);
    Element root = d.getRootElement();
    String koID = root.selectSingleNode("/serviceWareXml/knowledgeObj/@id").getText();
    String koName = root.selectSingleNode("/serviceWareXml/knowledgeObj/knowledgeObjName").getText();
    String koShortDesc = root.selectSingleNode("/serviceWareXml/knowledgeObj/knowledgeObjShortDesc").getText();
    ServiceWareAPI.updateKnowledgeObject(p_sessionId, koID, koName, koShortDesc, p_targetLocale);

    // now update the concepts
    List conceptNodes = root.selectNodes("/serviceWareXml/knowledgeObj/concept");
    for (int i = 0; i < conceptNodes.size(); i++) {
        Node conceptNode = (Node) conceptNodes.get(i);
        String conceptId = conceptNode.selectSingleNode("@id").getText();
        String conceptName = conceptNode.selectSingleNode("conceptName").getText();
        String conceptShortDesc = conceptNode.selectSingleNode("conceptShortDesc").getText();
        ServiceWareAPI.updateConceptObject(p_sessionId, conceptId, conceptName, conceptShortDesc,
                p_targetLocale);
    }
    XmlParser.fire(xmlp);
}

From source file:com.globalsight.everest.aligner.AlignerPackageOptions.java

License:Apache License

/**
 * Initializes this object from an XML string.
 *//* ww  w.  jav a2 s.c om*/
public void init(String p_options) throws Exception {
    XmlParser parser = null;
    Document dom = null;
    Element elem;
    List nodes;

    clearFilePairs();
    clearExtensions();

    try {
        parser = XmlParser.hire();
        dom = parser.parseXml(p_options);

        Element root = dom.getRootElement();

        m_packageName = root.elementText("packageName");

        elem = (Element) root.selectSingleNode("//extractionOptions");
        m_extractionOptions.m_formatType = elem.elementText("formatType");
        m_extractionOptions.m_rules = elem.elementText("rules");
        m_extractionOptions.m_sourceEncoding = elem.elementText("sourceEncoding");
        m_extractionOptions.m_targetEncoding = elem.elementText("targetEncoding");
        m_extractionOptions.m_sourceLocale = elem.elementText("sourceLocale");
        m_extractionOptions.m_targetLocale = elem.elementText("targetLocale");

        nodes = root.selectNodes("//extractionOptions//extension");
        for (int i = 0, max = nodes.size(); i < max; i++) {
            elem = (Element) nodes.get(i);

            String ext = elem.getText();

            addExtension(ext);
        }

        nodes = root.selectNodes("//filePair");
        for (int i = 0, max = nodes.size(); i < max; i++) {
            elem = (Element) nodes.get(i);

            FilePair pair = new FilePair(elem.elementText("source"), elem.elementText("target"));

            addFilePair(pair);
        }

        elem = (Element) root.selectSingleNode("//alignerOptions");
        m_alignerOptions.m_ignoreFormatting = elem.elementText("ignoreFormatting");
    } finally {
        XmlParser.fire(parser);
    }
}

From source file:com.globalsight.everest.aligner.AlignerPackageUploadOptions.java

License:Apache License

/**
 * Initializes this object from an XML string.
 *//*from w  w w  .  j a v a2 s.co m*/
public void init(String p_options) throws Exception {
    XmlParser parser = null;
    Document dom = null;
    Element elem;

    try {
        parser = XmlParser.hire();
        dom = parser.parseXml(p_options);

        Element root = dom.getRootElement();

        elem = (Element) root.selectSingleNode("//fileOptions");
        m_fileOptions.m_fileName = elem.elementText("fileName");

        elem = (Element) root.selectSingleNode("//tmOptions");
        m_tmOptions.m_tmName = elem.elementText("tmName");
        m_tmOptions.m_syncMode = elem.elementText("syncMode");
    } finally {
        XmlParser.fire(parser);
    }
}