0% found this document useful (0 votes)
27 views

XMLDOMParser

This Java class defines methods for parsing XML documents into a DOM representation and extracting element values. The getDocument method parses an XML string into a DOM Document object, catching any parsing exceptions. The getValue method retrieves the text value of the first child node of an element. The getTextNodeValue helper method recursively extracts the text value from a DOM node.

Uploaded by

Phê Pha Offical
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

XMLDOMParser

This Java class defines methods for parsing XML documents into a DOM representation and extracting element values. The getDocument method parses an XML string into a DOM Document object, catching any parsing exceptions. The getValue method retrieves the text value of the first child node of an element. The getTextNodeValue helper method recursively extracts the text value from a DOM node.

Uploaded by

Phê Pha Offical
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 2

import android.util.

Log;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import
javax.xml.parsers.ParserConfigurationException;
public class XMLDOMParser {
public Document getDocument(String xml)
{
Document document = null;
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
try{
DocumentBuilder db =
factory.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new
StringReader(xml));
is.setEncoding("UTF-8");
document = db.parse(is);
}catch(ParserConfigurationException e)
{
Log.e("Error: ", e.getMessage(), e);
return null;
}
catch (SAXException e) {
Log.e("Error: ", e.getMessage(), e);
return null;
}
catch(IOException e){
Log.e("Error: ", e.getMessage(), e);
return null;
}
return document;
}
public String getValue(Element item, String name)
{
NodeList nodes =
item.getElementsByTagName(name);
return this.getTextNodeValue(nodes.item(0));
}
private final String getTextNodeValue(Node elem)
{
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild();
child != null; child = child.getNextSibling() ){
if( child.getNodeType() ==
Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
}

You might also like