Example usage for org.w3c.dom Document getDocumentElement

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

Introduction

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

Prototype

public Element getDocumentElement();

Source Link

Document

This is a convenience attribute that allows direct access to the child node that is the document element of the document.

Usage

From source file:com.microsoft.tfs.core.clients.build.internal.utils.XamlHelper.java

public static Properties loadPartial(final String xaml) {
    final Properties properties = new Properties();

    try {/*from   ww w.  j  av  a2 s. c o m*/
        final Document document = DOMCreateUtils.parseString(xaml);
        final Element root = document.getDocumentElement();

        final NodeList nodes = root.getElementsByTagName("x:String"); //$NON-NLS-1$
        for (int i = 0; i < nodes.getLength(); i++) {
            final Element element = (Element) nodes.item(i);
            final String key = element.getAttribute("x:Key"); //$NON-NLS-1$
            final String value = element.getFirstChild().getNodeValue();
            properties.put(key, value);
        }
    } catch (final XMLException e) {
        log.error(
                MessageFormat.format(Messages.getString("XamlHelper.ExceptionParsingProcessParaemtersFormat"), //$NON-NLS-1$
                        xaml), e);
    }

    return properties;
}

From source file:resources.XmlToAnime.java

public static void ReadXml() {
    animes.clear();//w  ww  .  j a v  a  2  s  . co m
    if (sUrl.isEmpty() || sUrl == null) {
        throw new InternalError("Url should not be empty!");
    }

    try {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        //Document doc = (Document) dBuilder.parse(new URL(sUrl).openStream());
        //Document doc = (Document) dBuilder.parse

        InputStream input = getInput();
        if (input.available() > 0) {
            Document doc = (Document) dBuilder.parse(input);
            doc.getDocumentElement().normalize();
            NodeList nList = doc.getElementsByTagName("entry");

            for (int i = 0; i < nList.getLength(); i++) {
                Node nNode = nList.item(i);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Anime anime = new Anime();
                    Element eElement = (Element) nNode;
                    anime.setId(Integer.parseInt(eElement.getElementsByTagName("id").item(0).getTextContent()));
                    anime.setTitle(eElement.getElementsByTagName("title").item(0).getTextContent());
                    anime.setDescription(eElement.getElementsByTagName("synopsis").item(0).getTextContent());
                    anime.setEpisodes(Integer
                            .parseInt(eElement.getElementsByTagName("episodes").item(0).getTextContent()));
                    anime.setImageUrl(eElement.getElementsByTagName("image").item(0).getTextContent());
                    anime.setStartDate(eElement.getElementsByTagName("start_date").item(0).getTextContent());
                    anime.setEndDate(eElement.getElementsByTagName("end_date").item(0).getTextContent());

                    String temp = eElement.getElementsByTagName("status").item(0).getTextContent();
                    if (temp.toLowerCase().contains("finished")) {
                        anime.setStatus(AnimeStatus.FINISHED);
                    } else if (temp.toLowerCase().contains("currently")) {
                        anime.setStatus(AnimeStatus.CURRENTLY_AIRING);
                    }

                    anime.setAirDay(CalculateNextRelease.getAirDay(anime));
                    anime.setType(
                            Anime.TYPE.valueOf(eElement.getElementsByTagName("type").item(0).getTextContent()));
                    animes.add(anime);
                }
            }
        }

    } catch (SAXException | IOException | ParserConfigurationException e) {
        status = STATUS.ERROR;
        e.printStackTrace();
    }
}

From source file:uk.ac.diamond.shibbolethecpauthclient.Utils.java

/**
 * Helper method that deserializes and unmarshalls the message from the given stream. This
 * method has been adapted from {@code org.opensaml.ws.message.decoder.BaseMessageDecoder}.
 * //w  w w  .  j a v  a 2s.c  o  m
 * @param parserPool
 *The parser to use for unmarshalling the message
 * @param messageStream
 *Input stream containing the message
 * 
 * @return The in-bound message
 * 
 * @throws ClientProtocolException
 * thrown if there is a problem deserializing and unmarshalling the message
 */
static XMLObject unmarshallMessage(ParserPool parserPool, InputStream messageStream)
        throws ClientProtocolException {

    try {
        Document messageDoc = parserPool.parse(messageStream);
        Element messageElem = messageDoc.getDocumentElement();

        Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(messageElem);
        if (unmarshaller == null) {
            throw new ClientProtocolException(
                    "Unable to unmarshall message, no unmarshaller registered for message element "
                            + XMLHelper.getNodeQName(messageElem));
        }

        XMLObject message = unmarshaller.unmarshall(messageElem);

        return message;
    } catch (XMLParserException e) {
        throw new ClientProtocolException("Encountered error parsing message into its DOM representation", e);
    } catch (UnmarshallingException e) {
        throw new ClientProtocolException("Encountered error unmarshalling message from its DOM representation",
                e);
    }
}

From source file:Main.java

public static Element GetXmlDoc(String filePath) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;//from  www  .  ja v a  2s .c  o m
    try {
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    }
    Document doc = null;
    try {
        File f = new File(filePath);
        doc = db.parse(f);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return (Element) doc.getDocumentElement();
}

From source file:com.enioka.jqm.tools.ResourceParser.java

private static void importXml() throws NamingException {
    InputStream is = ResourceParser.class.getClassLoader().getResourceAsStream(Helpers.resourceFile);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

    try {/*  w  ww .j a va2s.co m*/
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(is);
        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName("resource");

        String jndiAlias = null, resourceClass = null, description = "no description", scope = null,
                auth = "Container", factory = null;
        boolean singleton = false;

        for (int i = 0; i < nList.getLength(); i++) {
            Node n = nList.item(i);
            Map<String, String> otherParams = new HashMap<String, String>();

            NamedNodeMap attrs = n.getAttributes();
            for (int j = 0; j < attrs.getLength(); j++) {
                Node attr = attrs.item(j);
                String key = attr.getNodeName();
                String value = attr.getNodeValue();

                if ("name".equals(key)) {
                    jndiAlias = value;
                } else if ("type".equals(key)) {
                    resourceClass = value;
                } else if ("description".equals(key)) {
                    description = value;
                } else if ("factory".equals(key)) {
                    factory = value;
                } else if ("auth".equals(key)) {
                    auth = value;
                } else if ("singleton".equals(key)) {
                    singleton = Boolean.parseBoolean(value);
                } else {
                    otherParams.put(key, value);
                }
            }

            if (resourceClass == null || jndiAlias == null || factory == null) {
                throw new NamingException("could not load the resource.xml file");
            }

            JndiResourceDescriptor jrd = new JndiResourceDescriptor(resourceClass, description, scope, auth,
                    factory, singleton);
            for (Map.Entry<String, String> prm : otherParams.entrySet()) {
                jrd.add(new StringRefAddr(prm.getKey(), prm.getValue()));
            }
            xml.put(jndiAlias, jrd);
        }
    } catch (Exception e) {
        NamingException pp = new NamingException("could not initialize the JNDI local resources");
        pp.setRootCause(e);
        throw pp;
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:Main.java

public static Document getDocument(String xmlString) {
    Document document = null;
    try {// w ww .j  av a  2 s.  c o m
        DocumentBuilder builder = docFactory.newDocumentBuilder();
        document = builder.parse(new ByteArrayInputStream(xmlString.getBytes()));
        document.getDocumentElement().normalize();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    return document;
}

From source file:com.microsoft.tfs.core.clients.build.internal.utils.XamlHelper.java

public static String updateProperties(final String originalXaml, final Properties properties) {
    final ArrayList keys = new ArrayList(properties.keySet());

    final Document document = DOMCreateUtils.parseString(originalXaml);
    final Element root = document.getDocumentElement();

    // first update any properties that we already have
    final NodeList nodes = root.getElementsByTagName("x:String"); //$NON-NLS-1$
    for (int i = 0; i < nodes.getLength(); i++) {
        final Element element = (Element) nodes.item(i);
        final String key = element.getAttribute("x:Key"); //$NON-NLS-1$
        element.getFirstChild().getNodeValue();

        if (properties.containsKey(key)) {
            keys.remove(key);/*w  w  w  . jav  a 2 s .c o  m*/
            element.getFirstChild().setNodeValue(properties.getProperty(key));
        }
    }

    // now add any new properties to the xaml
    for (final Iterator it = keys.iterator(); it.hasNext();) {
        final String key = (String) it.next();
        final Element element = DOMUtils.appendChild(root, "x:String"); //$NON-NLS-1$
        element.setAttributeNS(XAML_NAMESPACE, "x:Key", key); //$NON-NLS-1$
        element.setAttributeNS(XML_NAMESPACE, "xml:space", "preserve"); //$NON-NLS-1$ //$NON-NLS-2$
        DOMUtils.appendText(element, properties.getProperty(key));
    }

    return DOMSerializeUtils.toString(root, DOMSerializeUtils.INDENT).trim();
}

From source file:org.owasp.benchmark.tools.BenchmarkCrawler.java

public static List<HttpPost> parseHttpFile(CloseableHttpClient httpclient, InputStream http) throws Exception {
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    InputSource is = new InputSource(http);
    Document doc = docBuilder.parse(is);
    Node root = doc.getDocumentElement();

    List<HttpPost> posts = new ArrayList<HttpPost>();
    List<Node> tests = getNamedChildren("benchmarkTest", root);
    for (Node test : tests) {
        HttpPost post = parseHttpTest(httpclient, test);
        posts.add(post);/* www. j  av a  2 s  .c  om*/
    }
    return posts;
}

From source file:com.tascape.qa.th.android.model.UIA.java

public static WindowHierarchy parseHierarchy(InputStream in, UiAutomatorDevice device)
        throws SAXException, ParserConfigurationException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(in);

    Element doc = document.getDocumentElement();
    NodeList nl = doc.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);// w  w w.  jav  a 2 s  . co m
        UIANode uiNode = parseNode(node);
        if (uiNode != null) {
            WindowHierarchy hierarchy = new WindowHierarchy(uiNode);
            hierarchy.setRotation(doc.getAttribute("rotation"));
            LOG.debug("{}", hierarchy);
            hierarchy.setUiAutomatorDevice(device);
            return hierarchy;
        }
    }
    throw new UIAException("Cannot parse view hierarchy");
}

From source file:com.codebutler.farebot.mifare.Card.java

public static Card fromXml(String xml) throws Exception {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(xml)));

    Element rootElement = doc.getDocumentElement();

    CardType type = CardType.class.getEnumConstants()[Integer.parseInt(rootElement.getAttribute("type"))];
    byte[] id = Utils.hexStringToByteArray(rootElement.getAttribute("id"));
    Date scannedAt = rootElement.hasAttribute("scanned_at")
            ? new Date(Long.valueOf(rootElement.getAttribute("scanned_at")))
            : new Date(0);
    switch (type) {
    case MifareDesfire:
        return DesfireCard.fromXml(id, scannedAt, rootElement);
    case CEPAS://ww  w  .ja va2 s  .  c o  m
        return CEPASCard.fromXML(id, scannedAt, rootElement);
    case FeliCa:
        return FelicaCard.fromXml(id, scannedAt, rootElement);
    default:
        throw new UnsupportedOperationException("Unsupported card type: " + type);
    }
}