Parse XML string
In this chapter you will learn:
Parse XML String
The following code parses an XML data hard coded in the code.
First it wraps the string based XML data into a StringReader
.
Then the StringReader
object is set to org.xml.sax.InputSource
.
The actual parsing is done with DocumentBuilder
and returns
org.w3c.dom.Document
.
import java.io.StringReader;
/* j ava 2 s . c o m*/
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class Main {
public static void main(String[] args) throws Exception {
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
}
static String xmlRecords =
"<data>" +
" <employee>" +
" <name>Tom</name>"+
" <title>Manager</title>" +
" </employee>" +
" <employee>" +
" <name>Jerry</name>"+
" <title>Programmer</title>" +
" </employee>" +
"</data>";
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » XML