Java examples for XML:DOM
get Type as first element from XML DOM element
//package com.java2s; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { public static void main(String[] argv) throws Exception { String relativePath = "java2s.com"; String nodeName = "java2s.com"; System.out.println(getType(relativePath, nodeName)); }//from w ww . j a v a 2s .co m private static String nodeString = null; private static String path = System.getProperty("user.dir") + "/src/org/design/pattern/"; @SuppressWarnings("finally") public static String getType(String relativePath, String nodeName) { try { DocumentBuilderFactory dFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder = dFactory.newDocumentBuilder(); Document doc; doc = builder.parse(new File(path + relativePath)); NodeList nl = doc.getElementsByTagName(nodeName); Node classNode = nl.item(0).getFirstChild(); nodeString = classNode.getNodeValue().trim(); } catch (Exception e) { e.printStackTrace(); } finally { return nodeString; } } }