Search in sources :

Example 51 with DocumentBuilder

use of javax.xml.parsers.DocumentBuilder in project cw-android by commonsguy.

the class WeatherDemo method buildForecasts.

void buildForecasts(String raw) throws Exception {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(raw)));
    NodeList times = doc.getElementsByTagName("start-valid-time");
    for (int i = 0; i < times.getLength(); i++) {
        Element time = (Element) times.item(i);
        Forecast forecast = new Forecast();
        forecasts.add(forecast);
        forecast.setTime(time.getFirstChild().getNodeValue());
    }
    NodeList temps = doc.getElementsByTagName("value");
    for (int i = 0; i < temps.getLength(); i++) {
        Element temp = (Element) temps.item(i);
        Forecast forecast = forecasts.get(i);
        forecast.setTemp(new Integer(temp.getFirstChild().getNodeValue()));
    }
    NodeList icons = doc.getElementsByTagName("icon-link");
    for (int i = 0; i < icons.getLength(); i++) {
        Element icon = (Element) icons.item(i);
        Forecast forecast = forecasts.get(i);
        forecast.setIcon(icon.getFirstChild().getNodeValue());
    }
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilder(javax.xml.parsers.DocumentBuilder) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) StringReader(java.io.StringReader) Document(org.w3c.dom.Document)

Example 52 with DocumentBuilder

use of javax.xml.parsers.DocumentBuilder in project hackpad by dropbox.

the class XmlProcessor method toXml.

final Node toXml(String defaultNamespaceUri, String xml) throws org.xml.sax.SAXException {
    //    See ECMA357 10.3.1
    DocumentBuilder builder = null;
    try {
        String syntheticXml = "<parent xmlns=\"" + defaultNamespaceUri + "\">" + xml + "</parent>";
        builder = getDocumentBuilderFromPool();
        Document document = builder.parse(new org.xml.sax.InputSource(new java.io.StringReader(syntheticXml)));
        if (ignoreProcessingInstructions) {
            List<Node> list = new java.util.ArrayList<Node>();
            addProcessingInstructionsTo(list, document);
            for (Node node : list) {
                node.getParentNode().removeChild(node);
            }
        }
        if (ignoreComments) {
            List<Node> list = new java.util.ArrayList<Node>();
            addCommentsTo(list, document);
            for (Node node : list) {
                node.getParentNode().removeChild(node);
            }
        }
        if (ignoreWhitespace) {
            //    Apparently JAXP setIgnoringElementContentWhitespace() has a different meaning, it appears from the Javadoc
            //    Refers to element-only content models, which means we would need to have a validating parser and DTD or schema
            //    so that it would know which whitespace to ignore.
            //    Instead we will try to delete it ourselves.
            List<Node> list = new java.util.ArrayList<Node>();
            addTextNodesToRemoveAndTrim(list, document);
            for (Node node : list) {
                node.getParentNode().removeChild(node);
            }
        }
        NodeList rv = document.getDocumentElement().getChildNodes();
        if (rv.getLength() > 1) {
            throw ScriptRuntime.constructError("SyntaxError", "XML objects may contain at most one node.");
        } else if (rv.getLength() == 0) {
            Node node = document.createTextNode("");
            return node;
        } else {
            Node node = rv.item(0);
            document.getDocumentElement().removeChild(node);
            return node;
        }
    } catch (java.io.IOException e) {
        throw new RuntimeException("Unreachable.");
    } catch (javax.xml.parsers.ParserConfigurationException e) {
        throw new RuntimeException(e);
    } finally {
        if (builder != null)
            returnDocumentBuilderToPool(builder);
    }
}
Also used : Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) IOException(java.io.IOException) DocumentBuilder(javax.xml.parsers.DocumentBuilder)

Example 53 with DocumentBuilder

use of javax.xml.parsers.DocumentBuilder in project lucida by claritylab.

the class TREC13To16Parser method loadTargets.

/**
	 * Loads the target objects from a file.
	 * 
	 * @param filename file that contains the targets
	 * @return targets or <code>null</code>, if the file could not be parsed
	 */
public static TRECTarget[] loadTargets(String filename) {
    try {
        // create factory object
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // create DOM parser
        DocumentBuilder parser = factory.newDocumentBuilder();
        // parse file and build tree
        Document trecD = parser.parse(new File(filename));
        NodeList targetL = trecD.getElementsByTagName("target");
        TRECTarget[] targets = new TRECTarget[targetL.getLength()];
        for (int i = 0; i < targets.length; i++) {
            Element targetE = (Element) targetL.item(i);
            String targetId = targetE.getAttribute("id").trim();
            String targetDesc = targetE.getAttribute("text").trim();
            NodeList questionL = targetE.getElementsByTagName("q");
            TRECQuestion[] questions = new TRECQuestion[questionL.getLength()];
            for (int j = 0; j < questions.length; j++) {
                Element questionE = (Element) questionL.item(j);
                String questionId = questionE.getAttribute("id").trim();
                String type = questionE.getAttribute("type").trim();
                String questionString = questionE.getFirstChild().getNodeValue().trim();
                questions[j] = new TRECQuestion(questionId, type, questionString);
            }
            targets[i] = new TRECTarget(targetId, targetDesc, questions);
        }
        return targets;
    } catch (Exception e) {
        MsgPrinter.printErrorMsg("Failed to load or parse question file:");
        MsgPrinter.printErrorMsg(e.toString());
        return null;
    }
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) IOException(java.io.IOException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) File(java.io.File)

Example 54 with DocumentBuilder

use of javax.xml.parsers.DocumentBuilder in project che by eclipse.

the class JavaProject method decodeClasspathEntry.

public IClasspathEntry decodeClasspathEntry(String encodedEntry) {
    try {
        if (encodedEntry == null)
            return null;
        StringReader reader = new StringReader(encodedEntry);
        Element node;
        try {
            DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            node = parser.parse(new InputSource(reader)).getDocumentElement();
        } catch (SAXException e) {
            return null;
        } catch (ParserConfigurationException e) {
            return null;
        } finally {
            reader.close();
        }
        if (!node.getNodeName().equalsIgnoreCase(ClasspathEntry.TAG_CLASSPATHENTRY) || node.getNodeType() != Node.ELEMENT_NODE) {
            return null;
        }
        return ClasspathEntry.elementDecode(node, this, null);
    } catch (IOException e) {
        // bad format
        return null;
    }
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilder(javax.xml.parsers.DocumentBuilder) Element(org.w3c.dom.Element) IJavaElement(org.eclipse.jdt.core.IJavaElement) StringReader(java.io.StringReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException)

Example 55 with DocumentBuilder

use of javax.xml.parsers.DocumentBuilder in project che by eclipse.

the class RefactoringHistoryManager method getCachedDocument.

/**
	 * Returns the cached refactoring history document.
	 *
	 * @param path
	 *            the path of the document
	 * @param input
	 *            the input stream where to read the document
	 * @return the cached refactoring history document
	 * @throws SAXException
	 *             if an error occurs while parsing the history entry
	 * @throws IOException
	 *             if an input/output error occurs
	 * @throws ParserConfigurationException
	 *             if an error occurs in the parser configuration
	 */
private Document getCachedDocument(final IPath path, final InputStream input) throws SAXException, IOException, ParserConfigurationException {
    if (path.equals(fCachedPath) && fCachedDocument != null)
        return fCachedDocument;
    DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    parser.setErrorHandler(new DefaultHandler());
    final Document document = parser.parse(new InputSource(input));
    fCachedDocument = document;
    fCachedPath = path;
    return document;
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilder(javax.xml.parsers.DocumentBuilder) Document(org.w3c.dom.Document) DefaultHandler(org.xml.sax.helpers.DefaultHandler)

Aggregations

DocumentBuilder (javax.xml.parsers.DocumentBuilder)883 Document (org.w3c.dom.Document)694 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)622 Element (org.w3c.dom.Element)339 IOException (java.io.IOException)276 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)276 NodeList (org.w3c.dom.NodeList)267 InputSource (org.xml.sax.InputSource)238 SAXException (org.xml.sax.SAXException)235 Node (org.w3c.dom.Node)199 StringReader (java.io.StringReader)167 Test (org.junit.Test)127 DOMSource (javax.xml.transform.dom.DOMSource)102 File (java.io.File)99 ByteArrayInputStream (java.io.ByteArrayInputStream)86 InputStream (java.io.InputStream)73 ArrayList (java.util.ArrayList)72 StreamResult (javax.xml.transform.stream.StreamResult)65 Transformer (javax.xml.transform.Transformer)59 SAXParseException (org.xml.sax.SAXParseException)56