Example usage for org.dom4j.io XMLWriter write

List of usage examples for org.dom4j.io XMLWriter write

Introduction

In this page you can find the example usage for org.dom4j.io XMLWriter write.

Prototype

public void write(Object object) throws IOException 

Source Link

Document

Writes the given object which should be a String, a Node or a List of Nodes.

Usage

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  a  va  2s. c o 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;/* w w  w .j  a  va  2  s  .  c o  m*/

    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;/*from ww  w .  j a  v  a 2 s  .c  om*/

    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.util.Dom4jUtil.java

License:Apache License

public static String formatXML(Document document, String charset) {
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(charset);//from w  ww  . j  a v  a 2 s. co m
    StringWriter sw = new StringWriter();
    XMLWriter xw = new XMLWriter(sw, format);
    try {
        xw.write(document);
        xw.flush();
        xw.close();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return document.asXML();
    }

    return sw.toString();
}

From source file:com.globalsight.diplomat.util.XmlUtil.java

License:Apache License

public static String format(String xml, EntityResolver entityResolver) {
    XmlParser parser = XmlParser.hire();
    if (entityResolver != null) {
        parser.setEntityResolver(entityResolver);
    }//from  www.j  a  va 2  s . com
    org.dom4j.Document dom = parser.parseXml(xml);
    OutputFormat format = new OutputFormat();
    format.setNewlines(true);
    format.setIndent(true);

    StringWriter writer = new StringWriter();
    XMLWriter xmlWriter = new XMLWriter(writer, format);
    try {
        xmlWriter.write(dom);
        xmlWriter.close();
    } catch (IOException e) {
        return xml;
    } finally {
        try {
            xmlWriter.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    return writer.getBuffer().toString();
}

From source file:com.globalsight.everest.tm.exporter.TmxWriter.java

License:Apache License

/**
 * Returns the XML representation like Element.asXML() but without the
 * top-level tag./*w  w  w  . j a  v a2  s. co  m*/
 */
private static String getInnerXml(Element p_node, OutputFormat outputFormat) {
    StringBuffer result = new StringBuffer();

    List content = p_node.content();

    for (int i = 0, max = content.size(); i < max; i++) {
        Node node = (Node) content.get(i);

        // Work around a specific behaviour of DOM4J text nodes:
        // The text node asXML() returns the plain Unicode string,
        // so we need to encode entities manually.
        if (node.getNodeType() == Node.TEXT_NODE) {
            result.append(EditUtil.encodeXmlEntities(node.getText()));
        } else {
            // Note: DOM4J's node.asXML() constructs the same 2 objects.
            StringWriter out = new StringWriter();
            XMLWriter writer = new XMLWriter(out, outputFormat);

            try {
                writer.write(node);
            } catch (IOException ignore) {
            }

            result.append(out.toString());
        }
    }

    return result.toString();
}

From source file:com.globalsight.everest.workflow.WorkflowNodeParameter.java

License:Apache License

/**
  * Restores the <code>Element</code> to the original string.
  * //from w w  w  . java  2  s  . c om
  * @param element
  *            The Element.
  * @return The original string.
  */
public String restore(Element element) {
    StringWriter s = new StringWriter();
    XMLWriter reader = new XMLWriter(s);
    try {
        reader.write(element);
    } catch (IOException e) {
        c_category.error("Error occured when write the element, the element is " + element.toString());
        c_category.error("The stack of the error when write the element is ", e);
    }
    return s.toString().replaceAll(XML_ROOT_PRE, StringUtil.EMPTY_STRING).replaceAll(XML_ROOT_SUF,
            StringUtil.EMPTY_STRING);
}

From source file:com.globalsight.everest.workflow.WorkflowTemplateAdapter.java

License:Apache License

/**
 * Saves the workflow template xml to the file storage dir.
 * /*  www  .  j ava  2s  .c om*/
 * @param p_document
 *            - the xml document of the workflow template.
 * @param p_templateName
 *            - the workflow template name.
 * 
 */
private void saveXmlToFileStore(Document p_document, String p_templateName) {
    OutputFormat format = OutputFormat.createCompactFormat();
    XMLWriter writer = null;
    try {
        String aaa = AmbFileStoragePathUtils.getWorkflowTemplateXmlDir().getAbsolutePath();
        writer = new XMLWriter(
                new FileOutputStream(AmbFileStoragePathUtils.getWorkflowTemplateXmlDir().getAbsolutePath()
                        + File.separator + p_templateName + WorkflowConstants.SUFFIX_XML),
                format);
        writer.write(p_document);
    } catch (Exception e) {
        c_category.info("Exception occurs when saving the template xml to file storage");
    } finally {
        try {
            if (writer != null)
                writer.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:com.globalsight.smartbox.bussiness.process.Usecase02PreProcess.java

License:Apache License

/**
 * Convert csv/txt file to xml file/* ww w  .  j av  a  2 s.  c  o m*/
 * 
 * @param format
 * @param originFile
 * @return
 */
private String convertToXML(String format, File originFile) {
    String fileName = originFile.getName();
    // Save the converted file to temp directory
    String xmlFilePath = jobInfo.getTempFile() + File.separator
            + fileName.substring(0, fileName.lastIndexOf(".")) + ".xml";
    File xmlFile = new File(xmlFilePath);
    FileReader fr = null;
    FileInputStream fis = null;
    InputStreamReader isr = null;
    BufferedReader br = null;
    XMLWriter output = null;
    try {
        String encoding = FileUtil.guessEncoding(originFile);

        Document document = DocumentHelper.createDocument();
        Element aElement = document.addElement("root");
        aElement.addAttribute("BomInfo", encoding == null ? "" : encoding);

        if (encoding == null) {
            fr = new FileReader(originFile);
            br = new BufferedReader(fr);
        } else {
            fis = new FileInputStream(originFile);
            isr = new InputStreamReader(fis, encoding);
            br = new BufferedReader(isr);
        }

        String str;
        if ("csv".equals(format)) {
            while ((str = br.readLine()) != null) {
                String[] values = str.split("\",\"");
                values[0] = values[0].substring(1);
                values[10] = values[10].substring(0, values[10].length() - 1);
                writeRow(aElement, values);
            }
        } else {
            while ((str = br.readLine()) != null) {
                str = str + "*";
                String[] values = str.split("\\|");
                values[10] = values[10].substring(0, values[10].lastIndexOf("*"));
                writeRow(aElement, values);
            }
        }

        output = new XMLWriter(new FileOutputStream(xmlFile));
        output.write(document);
    } catch (Exception e) {
        String message = "Failed to convert to XML, File Name: " + originFile.getName();
        LogUtil.fail(message, e);
        return null;
    } finally {
        try {
            if (output != null) {
                output.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
            if (fr != null) {
                fr.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return xmlFile.getPath();
}

From source file:com.googlecode.fascinator.common.sax.SafeSAXReader.java

License:Open Source License

/**
 * Convert node to string/* w  ww.ja  v  a2  s .  c om*/
 * 
 * @param outDoc Node to be converted
 * @return String of the converted node
 * @throws IOException if the conversion fail
 */
public String docToString(Node outDoc) throws IOException {
    Writer osw = new StringWriter();
    OutputFormat opf = new OutputFormat("", false, "UTF-8");
    opf.setSuppressDeclaration(true);
    opf.setExpandEmptyElements(true);
    XMLWriter writer = new XMLWriter(osw, opf);
    writer.setEscapeText(false);
    writer.write(outDoc);
    writer.close();

    return osw.toString();
}