Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    private static Logger logger = Logger.getLogger(new Exception().getStackTrace()[0].getClassName());

    public static String getAttribute(String xmlStr, String tagName, String attrName) {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(false); // never forget this!
        Document doc = null;
        DocumentBuilder builder = null;
        String value = null;

        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 {
                value = nodeList.item(0).getAttributes().getNamedItem(attrName).getNodeValue();
                logger.debug("value of " + tagName + " attribute: " + attrName + " = " + value);
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

        return value;
    }
}