Example usage for org.w3c.dom Document normalize

List of usage examples for org.w3c.dom Document normalize

Introduction

In this page you can find the example usage for org.w3c.dom Document normalize.

Prototype

public void normalize();

Source Link

Document

Puts all Text nodes in the full depth of the sub-tree underneath this Node, including attribute nodes, into a "normal" form where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.

Usage

From source file:edu.harvard.i2b2.fhir.Utils.java

public static String getStringFromDocument(Document doc) {
    try {// w  ww .  j a v  a  2  s .  c om
        doc.normalize();
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        //
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        int indent = 2;
        if (indent > 0) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
                    Integer.toString(indent));
        }
        //

        transformer.transform(domSource, result);
        return writer.toString();
    } catch (TransformerException ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:Main.java

public static Document load(String file) {
    try {//from   w  w  w .j a  va  2  s .c  om
        Document document = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        dbf.setNamespaceAware(false);
        DocumentBuilder builder = dbf.newDocumentBuilder();
        document = builder.parse(new File(file));
        document.normalize();
        return document;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static String getCofigValue(Activity activity, String filename, String keyName) {
    String ret = "";
    InputStream is = activity.getClass().getResourceAsStream(filename);
    if (is != null) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;

        try {/*from  w  w  w.j  a v  a2  s  .c  om*/
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Document doc = null;

        try {
            doc = builder.parse(is);
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        doc.normalize();
        NodeList list = doc.getElementsByTagName(keyName);
        if (list != null && list.getLength() > 0) {
            ret = list.item(0).getFirstChild().getNodeValue();
        }
    }
    return ret;
}

From source file:org.apache.lens.regression.util.Util.java

public static final void prettyPrint(Document xml)
        throws TransformerFactoryConfigurationError, TransformerException {
    xml.normalize();
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    StreamResult output = new StreamResult(new File(localFile));
    Source input = new DOMSource(xml);
    transformer.transform(input, output);
}

From source file:org.apache.lens.regression.util.Util.java

public static void changeConfig(HashMap<String, String> map, String remotePath) throws Exception {

    Path p = Paths.get(remotePath);
    String fileName = p.getFileName().toString();
    backupFile = localFilePath + "backup-" + fileName;
    localFile = localFilePath + fileName;
    log.info("Copying " + remotePath + " to " + localFile);
    remoteFile("get", remotePath, localFile);
    Files.copy(new File(localFile).toPath(), new File(backupFile).toPath(), REPLACE_EXISTING);

    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = docBuilder.parse(new FileInputStream(localFile));
    doc.normalize();

    NodeList rootNodes = doc.getElementsByTagName("configuration");
    Node root = rootNodes.item(0);
    Element rootElement = (Element) root;
    NodeList property = rootElement.getElementsByTagName("property");

    for (int i = 0; i < property.getLength(); i++) { //Deleting redundant properties from the document
        Node prop = property.item(i);
        Element propElement = (Element) prop;
        Node propChild = propElement.getElementsByTagName("name").item(0);

        Element nameElement = (Element) propChild;
        if (map.containsKey(nameElement.getTextContent())) {
            rootElement.removeChild(prop);
            i--;/*from   w w  w.  j a v a  2  s  .  c  o  m*/
        }
    }

    Iterator<Entry<String, String>> ab = map.entrySet().iterator();
    while (ab.hasNext()) {
        Entry<String, String> entry = ab.next();
        String propertyName = entry.getKey();
        String propertyValue = entry.getValue();
        System.out.println(propertyName + " " + propertyValue + "\n");
        Node newNode = doc.createElement("property");
        rootElement.appendChild(newNode);
        Node newName = doc.createElement("name");
        Element newNodeElement = (Element) newNode;

        newName.setTextContent(propertyName);
        newNodeElement.appendChild(newName);

        Node newValue = doc.createElement("value");
        newValue.setTextContent(propertyValue);
        newNodeElement.appendChild(newValue);
    }
    prettyPrint(doc);
    remoteFile("put", remotePath, localFile);
}

From source file:Main.java

public static void DocumentToFile(final Document doc, File file) {
    // FileWriter writer = null;
    OutputStreamWriter outputStreamWriter = null;

    try {/* w  ww .j av a 2 s . co m*/
        // writer = new FileWriter(file);

        FileOutputStream fileOutputStream = new FileOutputStream(file);
        outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");

    } catch (Exception e) {
        System.err.println(e);

        return;
    }

    //Result l_s = new StreamResult(writer);
    Result l_s = new StreamResult(outputStreamWriter);

    doc.normalize();

    try {
        TransformerFactory.newInstance().newTransformer().transform(new DOMSource(doc), l_s);

        outputStreamWriter.close();
        //writer.close();
    } catch (Exception e) {
        System.err.println(e);

        return;
    }
}

From source file:Main.java

/**
 *
 *
 * @param obj .../*from  w  ww .  j a v  a2s. co m*/
 *
 * @return ...
 *
 * @throws SAXException ...
 * @throws IOException ...
 * @throws ParserConfigurationException ...
 */
public static Document parseXml(Object obj) throws SAXException, IOException, ParserConfigurationException {
    if (domBuilderFactory == null) {
        domBuilderFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    }

    DocumentBuilder parser = domBuilderFactory.newDocumentBuilder();
    Document doc = null;

    if (obj instanceof String) {
        try {
            // first try to interpret string as URL
            new URL(obj.toString());

            doc = parser.parse(obj.toString());
        } catch (MalformedURLException nourl) {
            // if not a URL, maybe it is the XML itself
            doc = parser.parse(new InputSource(new StringReader(obj.toString())));
        }
    } else if (obj instanceof InputStream) {
        doc = parser.parse(new InputSource((InputStream) obj));
    } else if (obj instanceof Reader) {
        doc = parser.parse(new InputSource((Reader) obj));
    }

    doc.normalize();

    return doc;
}

From source file:com.jaeksoft.searchlib.util.XPathParser.java

public XPathParser(InputSource inputSource) throws SAXException, IOException, ParserConfigurationException {
    this(null, DomUtils.readXml(inputSource, true));
    Document document = (Document) rootNode;
    document.normalize();
}

From source file:Importers.ImportReportCompiler.java

@Override
public DefaultMutableTreeNode readFile(File importFile) {
    System.out.println("==ImportReportCompiler=readFile");
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("vulns");
    try {//from  w w w  .  j  av  a2  s  .  c  o  m

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(importFile);
        doc.normalize();

        NodeList vulns_list = doc.getElementsByTagName("vuln");
        for (int i = 0; i < vulns_list.getLength(); i++) {
            Node vuln_node = vulns_list.item(i);
            Vulnerability vuln = getVuln(vuln_node);
            root.add(new DefaultMutableTreeNode(vuln));
        }

    } catch (ParserConfigurationException ex) {
        Logger.getLogger(NessusV2XMLImporter.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(NessusV2XMLImporter.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(NessusV2XMLImporter.class.getName()).log(Level.SEVERE, null, ex);
    }

    return root;
}

From source file:matteroverdrive.gui.pages.PageGuideDescription.java

private void loadGuideInfo(int guideID) {
    pages.clear();/*  www. j  a va 2  s.c om*/

    if (guideID >= 0) {
        MOGuideEntry entry = MatterOverdriveGuide.getQuide(guideID);
        InputStream descriptionStream = entry.getDescriptionStream();
        if (descriptionStream != null) {
            try {
                Document document = builder.parse(descriptionStream);
                document.normalize();
                Element rootNode = (Element) document.getElementsByTagName("entry").item(0);
                NodeList pagesNodes = rootNode.getElementsByTagName("page");
                Map<String, String> stylesheetMap = loadStyleSheetMap(rootNode);

                for (int i = 0; i < pagesNodes.getLength(); i++) {
                    GuideElementPage page = new GuideElementPage();
                    page.setGUI((MOGuiBase) gui);
                    page.loadElement(entry, (Element) pagesNodes.item(i), stylesheetMap, sizeX, sizeY);
                    pages.add(page);
                }

            } catch (SAXException e) {
                MatterOverdrive.log.log(Level.ERROR, e, "XML for guide entry %s is not valid",
                        entry.getDisplayName());
            } catch (IOException e) {
                MatterOverdrive.log.log(Level.ERROR, e,
                        "there was a problem reading language file for entry %s", entry.getDisplayName());
            }
        } else {
            MatterOverdrive.log.warn("Guide Entry file for %s missing at: %s", entry.getDisplayName(),
                    entry.getDescriptionPath("language"));
        }
    }
}