Using Document Builder to Access an XML Tag Value

Imports…


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.xml.sax.InputSource;
import java.io.StringReader;
import org.w3c.dom.Document;
import org.w3c.dom.CharacterData;

Method…


	private static String findXMLTagValueFromXML(String xml, String tag) throws Exception {
		DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		InputSource is = new InputSource();
	    is.setCharacterStream(new StringReader(xml));
	    Document doc = db.parse(is);
	    CharacterData child = (CharacterData) doc.getElementsByTagName(tag).item(0).getFirstChild();
	    return child.getData();
	}