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:gpms.utils.PolicyTestUtil.java

/**
 * This creates the expected XACML response from a file
 *
 * @param rootDirectory//from  w w w  . j av  a  2 s  . com
 *            root directory of the response files
 * @param versionDirectory
 *            version directory of the response files
 * @param responseId
 *            response file name
 * @return ResponseCtx or null if any error
 */
public static ResponseCtx createResponse(String rootDirectory, String versionDirectory, String responseId) {

    File file = new File(".");
    try {
        String filePath = file.getCanonicalPath() + File.separator + TestConstants.RESOURCE_PATH
                + File.separator + rootDirectory + File.separator + versionDirectory + File.separator
                + TestConstants.RESPONSE_DIRECTORY + File.separator + responseId;

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        DocumentBuilder db = factory.newDocumentBuilder();
        Document doc = db.parse(new FileInputStream(filePath));
        return ResponseCtx.getInstance(doc.getDocumentElement());
    } catch (Exception e) {
        log.error("Error while reading expected response from file ", e);
        // ignore any exception and return null
    }

    return null;
}

From source file:com.valco.utility.FacturasUtility.java

public static void agregarDatosDeTimbrado(Facturas factura, String xml)
        throws ParserConfigurationException, SAXException, IOException, ParseException {
    String folioFiscal = null;//w ww  .ja v a  2s  .  co m
    Date fechaTimbrado = new Date();
    String selloCFD = null;
    String noCertificadoSat = null;
    String selloSat = null;
    SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    InputStream inputXml = new ByteArrayInputStream(xml.getBytes("UTF-8"));
    org.w3c.dom.Document doc = dBuilder.parse(inputXml);
    doc.getDocumentElement().normalize();

    NodeList nList = doc.getElementsByTagName("tfd:TimbreFiscalDigital");

    for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);

        System.out.println("\nCurrent Element :" + nNode.getNodeName());

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

            Element eElement = (Element) nNode;

            folioFiscal = eElement.getAttribute("UUID");
            fechaTimbrado = formatDate.parse(eElement.getAttribute("FechaTimbrado"));
            selloCFD = eElement.getAttribute("selloCFD");
            noCertificadoSat = eElement.getAttribute("noCertificadoSAT");
            selloSat = eElement.getAttribute("selloSAT");

            factura.setFolioFiscal(folioFiscal);
            factura.setFechaTimbrado(fechaTimbrado);
            factura.setSelloCdfi(selloCFD);
            factura.setNoSerieCertSat(noCertificadoSat);
            factura.setSelloSat(selloSat);
        }
    }
}

From source file:gov.nih.nci.cagrid.opensaml.SAMLObject.java

/**
 *  Allows parsing of objects of a particular minor version from a stream of XML
 *
 * @param  in                   A stream containing XML
 * @param  minor                The minor version of the incoming object
 * @return                      The root of the XML document instance
 * @exception  SAMLException  Raised if an exception occurs while constructing
 *                              the object
 *//*from w  w  w .j  a  v  a  2s.com*/
static protected Element fromStream(InputStream in, int minor) throws SAMLException {
    try {
        Document doc = XML.parserPool.parse(new InputSource(in),
                (minor == 1) ? XML.parserPool.getSchemaSAML11() : XML.parserPool.getSchemaSAML10());
        return doc.getDocumentElement();
    } catch (Exception e) {
        NDC.push("fromStream");
        Logger.getLogger(SAMLObject.class.getName())
                .error("caught an exception while parsing a stream:\n" + e.getMessage());
        NDC.pop();
        throw new MalformedException("SAMLObject.fromStream() caught exception while parsing a stream", e);
    }
}

From source file:net.sourceforge.dita4publishers.word2dita.Word2DitaValidationHelper.java

/**
 * @param pkg//from  w  ww.j a  v  a  2 s. co  m
 * @param bosOptions
 * @throws Exception 
 */
static void addCommentFileRelationship(ZipComponents zipComponents, BosConstructionOptions bosOptions)
        throws Exception {
    ZipComponent comp = zipComponents.getEntry(DocxConstants.DOCUMENT_XML_RELS_PATH);
    Document doc = zipComponents.getDomForZipComponent(bosOptions, comp);
    Element docElem = doc.getDocumentElement();
    NodeList nl = docElem.getElementsByTagNameNS(DocxConstants.RELS_NS, "Relationship");
    boolean foundCommentRel = false;
    for (int i = 0; i < nl.getLength(); i++) {
        Element elem = (Element) nl.item(i);
        String type = elem.getAttribute("Type");
        if (DocxConstants.COMMENT_REL_TYPE.equals(type)) {
            foundCommentRel = true;
            break;
        }
    }
    if (!foundCommentRel) {
        Element elem = doc.createElementNS(DocxConstants.RELS_NS, "Relationship");
        elem.setAttribute("Type", DocxConstants.COMMENT_REL_TYPE);
        elem.setAttribute("Id", "rId" + (nl.getLength() + 1));
        elem.setAttribute("Target", "comments.xml");
        docElem.appendChild(elem);
        // System.out.println(IOUtils.toString(DomUtil.serializeToInputStream(doc, "utf-8")));
        comp.setDom(doc);
    }

}

From source file:com.hp.mqm.atrf.core.configuration.FetchConfiguration.java

public static FetchConfiguration loadPropertiesFromFile(String pathName) {

    FetchConfiguration configuration = new FetchConfiguration();

    try {/*w w  w  .  jav  a  2 s .  c om*/
        File inputFile = new File(pathName);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

        Document doc = dBuilder.parse(inputFile);
        doc.getDocumentElement().normalize();
        Node root = doc.getDocumentElement();
        if (!root.getNodeName().equals("conf")) {
            throw new RuntimeException("Missing root element <conf> in file : " + pathName);
        }
        parseNodes(root, root.getNodeName(), configuration);
    } catch (IOException e) {
        throw new RuntimeException("Failed to read configuration file : " + pathName, e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Failed to parse configuration file : " + pathName, e);
    } catch (SAXException e) {
        throw new RuntimeException("Failed to parse configuration file : " + pathName, e);
    }
    return configuration;
}

From source file:client.QueryLastFm.java

License:asdf

public static void findSimilarTracks(PrintWriter track_id_out, String sourceMbid, String trackName,
        String artistName) throws Exception {
    String destMbid;//from w  ww  .  j  a  v  a  2s  . com
    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {
        Thread.sleep(50); //1000 milliseconds is one second.
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
    try {
        URI uri = new URIBuilder().setScheme("http").setHost("ws.audioscrobbler.com").setPath("/2.0/")
                .setParameter("method", "track.getsimilar").setParameter("artist", artistName)
                .setParameter("track", trackName).setParameter("limit", "10")
                .setParameter("api_key", "88858618961414f8bec919bddd057044").build();

        // new URIBuilder().
        HttpGet request = new HttpGet(uri);

        // request.
        // This is useful for last.fm logging and preventing them from blocking this client
        request.setHeader(HttpHeaders.USER_AGENT,
                "nileshmore@gatech.edu - ClassAssignment at GeorgiaTech Non-commercial use");

        CloseableHttpResponse response = httpclient.execute(request);

        int statusCode = response.getStatusLine().getStatusCode();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        try {
            if (statusCode == 200) {
                HttpEntity entity1 = response.getEntity();
                BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));
                Document document = builder.parse((response.getEntity().getContent()));
                Element root = document.getDocumentElement();
                root.normalize();

                NodeList mbidList = root.getElementsByTagName("mbid");
                // System.out.println("mbid" + mbidList.getLength());

                for (int n = 0; n < mbidList.getLength(); n++) {
                    Node attribute = mbidList.item(n);
                    if (mbidList.item(n).hasChildNodes()) {
                        if (mbidList.item(n).getParentNode().getNodeName().matches("track")) // to get correct mbid
                        {
                            destMbid = mbidList.item(n).getFirstChild().getNodeValue();
                            // track_id_out.print(sourceMbid);
                            // track_id_out.print(",");
                            // track_id_out.println(destMbid);
                            if (isAlreadyInserted(sourceMbid, destMbid)) //  if not inserted , insert into map
                            {
                                // System.out.println(sourceMbid + "---"  + destMbid);
                                // track_id_out.print(sourceMbid);
                                // track_id_out.print(",");
                                // track_id_out.println(destMbid);
                                // continue;
                            }
                            /*if(isAlreadyInserted(sourceMbid, destMbid))
                            {
                              System.out.println("Ok got the match !!");
                            }*/
                            else {
                                track_id_out.print(sourceMbid);
                                track_id_out.print(",");
                                track_id_out.println(destMbid); //
                                // track_id_out.print(",");
                                // track_id_out.println("Undirected");
                            }
                            // track_id_out.print()
                        }
                    }
                }

            }

        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

}

From source file:net.roboconf.agent.internal.misc.UserDataUtils.java

private static String getValueOfTagInXMLFile(String filePath, String tagName)
        throws ParserConfigurationException, SAXException, IOException {

    File fXmlFile = new File(filePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);

    // Optional, but recommended
    // Read this: http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
    doc.getDocumentElement().normalize();

    NodeList nList = doc.getElementsByTagName(tagName);
    String valueOfTagName = "";

    for (int temp = 0; temp < nList.getLength(); temp++) {
        Node nNode = nList.item(temp);
        valueOfTagName = nNode.getTextContent();
    }// w w  w.j  a va  2  s  . co m

    return valueOfTagName;
}

From source file:net.sourceforge.dita4publishers.word2dita.Word2DitaValidationHelper.java

/**
 * @param zipComponents//  w  w w .  j  a  v a 2 s . c o  m
 * @param bosOptions
 * @throws Exception 
 */
public static void addCommentFileContentType(ZipComponents zipComponents, BosConstructionOptions bosOptions)
        throws Exception {

    /*
     *   <Override
    PartName="/word/comments.xml"
    ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/>
            
     */

    ZipComponent comp = zipComponents.getEntry("[Content_Types].xml");
    Document doc = zipComponents.getDomForZipComponent(bosOptions, comp);
    Element docElem = doc.getDocumentElement();
    String contentTypesNs = "http://schemas.openxmlformats.org/package/2006/content-types";
    NodeList nl = docElem.getElementsByTagNameNS(contentTypesNs, "Override");
    boolean foundCommentType = false;
    for (int i = 0; i < nl.getLength(); i++) {
        Element elem = (Element) nl.item(i);
        String partName = elem.getAttribute("PartName");
        if (DocxConstants.COMMENTS_PARTNAME.equals(partName)) {
            foundCommentType = true;
            break;
        }
    }
    if (!foundCommentType) {
        Element elem = doc.createElementNS(contentTypesNs, "Override");
        elem.setAttribute("PartName", DocxConstants.COMMENTS_PARTNAME);
        elem.setAttribute("ContentType", DocxConstants.COMMENTS_CONTENT_TYPE);
        docElem.appendChild(elem);
        comp.setDom(doc);
    }
}

From source file:Main.java

/**
 * Locates the attribute defined by the XPath expression in the XML file and replaces it with the passed value.
 * @param fileName The XML file to update.
 * @param xPathExpression An XPath expression that locates the attribute to update.
 * @param attributeName The name of the attribute to update.
 * @param value The value to update the attribute to.
 *///from  www.  ja  v a 2  s  . com
public static void updateAttributeInXMLFile(String fileName, String xPathExpression, String attributeName,
        String value) {
    try {
        Document document = parseXML(new File(fileName));
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression xpathExpression = xpath.compile(xPathExpression);
        Element element = (Element) xpathExpression.evaluate(document, NODE);

        element.getAttributeNode(attributeName).setValue(value);
        writeElement(document.getDocumentElement(), fileName);

    } catch (Exception e) {
        throw new RuntimeException("Failed to extract element from:" + fileName, e);
    }
}

From source file:com.cisco.dvbu.ps.common.adapters.util.XmlUtils.java

public static Document stringToDocument(String xmlString) throws Exception {
    // Insure that there are no carriage return and line feeds in the string.
    xmlString = xmlString.replaceAll("[\n\r]", "");

    // Convert from string to Document
    Document doc = null;
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;/*from   w w w.  j  av a 2  s  . c o  m*/
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(new ByteArrayInputStream(xmlString.getBytes()));
        doc.getDocumentElement().normalize();
    } catch (Exception e) {
        doc = null;
        log.error("String to Xml Transformation error!" + e.getMessage());
        throw e;
    }
    return doc;
}