Example usage for org.w3c.dom Document getElementsByTagName

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

Introduction

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

Prototype

public NodeList getElementsByTagName(String tagname);

Source Link

Document

Returns a NodeList of all the Elements in document order with a given tag name and are contained in the document.

Usage

From source file:biz.webgate.tools.urlfetcher.URLFetcher.java

public static void parseContent(int maxPictureHeight, PageAnalyse analyse, InputStream is)
        throws FetcherException {
    try {/*from  w w w  .ja va  2s  .  c  o m*/
        Document doc;
        DOMParser dpHTML = new DOMParser();
        dpHTML.setProperty("http://cyberneko.org/html/properties/default-encoding", "utf-8");
        dpHTML.parse(new InputSource(is));
        doc = dpHTML.getDocument();

        NodeList ndlMet = doc.getElementsByTagName("meta");
        NodeList ndlTitle = doc.getElementsByTagName("title");
        NodeList ndlImage = doc.getElementsByTagName("img");

        check4OpenGraphTags(ndlMet, analyse);
        checkDescription(analyse, ndlMet);
        checkTitle(analyse, ndlTitle);
        checkImage(analyse, ndlImage, maxPictureHeight);
    } catch (Exception e) {
        throw new FetcherException(e);
    }
}

From source file:com.esri.geoevent.solutions.adapter.cot.CoTUtilities.java

public static ArrayList<CoTTypeDef> getCoTTypeMap(InputStream mapInputStream)
        throws ParserConfigurationException, SAXException, IOException {

    ArrayList<CoTTypeDef> types = null;

    String content = getStringFromFile(mapInputStream);

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource source = new InputSource();
    source.setCharacterStream(new StringReader(content));
    Document doc = db.parse(source);
    NodeList nodeList = doc.getElementsByTagName("types");
    types = typeBreakdown(nodeList.item(0));
    return types;
}

From source file:Main.java

public static void testx() {
    try {/*from  w  w w.  j  a  v  a 2  s  .  com*/
        File fXmlFile = new File("C:\\Users\\is96092\\Desktop\\music\\Megaman2.xml");
        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();

        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

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

        System.out.println("----------------------------");

        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;

                System.out.println("Staff id : " + eElement.getAttribute("id"));
                System.out.println(
                        "First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
                System.out.println(
                        "Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
                System.out.println(
                        "Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
                System.out.println(
                        "Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static String setAttribute(String xmlStr, String tagName, String attrName, String newValue) {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(false); // never forget this!
    int i, j;/*from w  w  w  .  j a va  2 s  .c  o  m*/
    Document doc = null;
    DocumentBuilder builder = null;

    StringWriter stringOut = new StringWriter();
    try {
        builder = domFactory.newDocumentBuilder();
        doc = builder.parse(new ByteArrayInputStream(xmlStr.getBytes()));
        // Get the root element
        Node rootNode = doc.getFirstChild();
        NodeList nodeList = doc.getElementsByTagName(tagName);
        if ((nodeList.getLength() == 0) || (nodeList.item(0).getAttributes().getNamedItem(attrName) == null)) {
            logger.error("Either node " + tagName + " or attribute " + attrName + " not found.");
        } else {
            logger.debug("value of " + tagName + " attribute: " + attrName + " = "
                    + nodeList.item(0).getAttributes().getNamedItem(attrName).getNodeValue());
            nodeList.item(0).getAttributes().getNamedItem(attrName).setNodeValue(newValue);

            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(stringOut);
            // StreamResult result = new StreamResult(new File(filepath));
            transformer.transform(source, result);
            logger.debug("Updated XML: \n" + stringOut.toString());
        }
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }

    return stringOut.toString();
}

From source file:Main.java

public static void ReadXMLFile()

{

    try {/*  w  ww  . jav  a 2 s .c om*/

        File fXmlFile = new File("D:\\FAR_Documents\\__Startamap\\Home.xml");
        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();

        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

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

        System.out.println("----------------------------");

        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;

                System.out.println("Staff id : " + eElement.getAttribute("id"));
                System.out.println(
                        "First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
                System.out.println(
                        "Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
                System.out.println(
                        "Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
                System.out.println(
                        "Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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 ww .j a va  2s  . c  o m*/
            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:edu.ku.brc.util.thumbnails.Thumbnailer.java

/**
 * /*from  w  w  w.java 2  s. co  m*/
 */
private static void readIconMap() {
    availableIcons = new HashMap<String, String>();
    fallbackIcons = new HashMap<String, String>();

    File mimeTypeFile = XMLHelper.getConfigDir("mime_icons.xml");
    if (mimeTypeFile.exists()) {
        try {
            Document registry = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(mimeTypeFile);
            NodeList mimeNodes = registry.getElementsByTagName("mimetype");
            for (int i = 0; i < mimeNodes.getLength(); ++i) {
                Node mimeNode = mimeNodes.item(i);
                Node iconNameNode = mimeNode.getAttributes().getNamedItem("icon");
                Node fallbackNode = mimeNode.getAttributes().getNamedItem("fallback");
                String iconName = iconNameNode.getNodeValue();
                String fbStr = fallbackNode != null ? fallbackNode.getNodeValue() : null;
                boolean isFallBack = StringUtils.isNotEmpty(fbStr) && fbStr.equals("true");
                NodeList extNodes = mimeNode.getChildNodes();
                for (int j = 0; j < extNodes.getLength(); ++j) {
                    Node extNode = extNodes.item(j);
                    String ext = extNode.getTextContent().trim();
                    if (StringUtils.isNotEmpty(ext)) {
                        if (isFallBack) {
                            fallbackIcons.put(ext, iconName);
                        } else {
                            availableIcons.put(ext, iconName);
                        }
                    }
                }
            }
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.dasein.cloud.terremark.TerremarkMethod.java

private static ParsedError parseErrorResponse(String responseBody) throws CloudException, InternalException {
    try {/* w  w  w.jav a  2 s  . c  om*/
        ByteArrayInputStream bas = new ByteArrayInputStream(responseBody.getBytes());

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser = factory.newDocumentBuilder();
        Document doc = parser.parse(bas);

        bas.close();

        Node errorNode = doc.getElementsByTagName(ERROR_TAG).item(0);
        ParsedError error = new ParsedError();
        if (errorNode != null) {
            error.message = errorNode.getAttributes().getNamedItem(MESSAGE_ATTR).getNodeValue();
            error.code = Integer
                    .parseInt(errorNode.getAttributes().getNamedItem(MAJOR_CODE_ATTR).getNodeValue());
        }

        return error;
    } catch (IOException e) {
        throw new CloudException(e);
    } catch (ParserConfigurationException e) {
        throw new CloudException(e);
    } catch (SAXException e) {
        throw new CloudException(e);
    }
}

From source file:Main.java

/**
 * Method to delete old elements and add new elements in target file based on tag name of source file.
 *
 * @param source//w w  w  . j  a  v a2s.  c  om
 * @param target
 * @param sourceTagName
 * @param targetTagNameParent
 * @param targetTagNameChild
 * @return document
 * @throws ParseException
 */
public static Document addNewElements(Document source, Document target, String sourceTagName,
        String targetTagNameParent, String targetTagNameChild, List<String> ignoreList) throws ParseException { //list for attributes to be more dynamic if reuse
    //remove old entries 
    target = removeAllOptions(target);
    // add new entries
    NodeList nameList = source.getElementsByTagName(sourceTagName);
    NodeList parents = target.getElementsByTagName(targetTagNameParent);
    Element parent = (Element) parents.item(0); // g:options - only 1
    // element
    //add space placeholder as first entry
    Element o = target.createElement(targetTagNameChild);
    o.setAttribute("g:value", "");
    o.setAttribute("g:label", "");
    parent.appendChild(o);

    for (int i = 0; i < nameList.getLength(); i++) {
        String value = nameList.item(i).getTextContent();
        if (value != null && !value.equals("") && !ignoreList.contains(value)) {
            Element p = target.createElement(targetTagNameChild);
            p.setAttribute("g:value", value);
            p.setAttribute("g:label", value);
            parent.appendChild(p);
        }
    }
    return changeDate(target);
}

From source file:Main.java

private static void addEntry(String file_path, String operation, String key, String value) {

    Document doc = getDocument(file_path);
    if (doc == null) {
        return;/*ww  w.j av  a2 s .c om*/
    }

    Element entry_elem = doc.createElement("Entry");
    entry_elem.setAttribute("Type", operation);
    entry_elem.setAttribute("Key", key);
    if (operation.equals("STORE")) {
        entry_elem.appendChild(doc.createTextNode(value));
    }

    Element log_element = (Element) doc.getElementsByTagName("Log").item(0);
    log_element.appendChild(entry_elem);

    saveFile(file_path, doc);

}