Java parse xml file/string/**
* @author lautturi.com
* Java example: parse xml string in java
*/
import java.io.IOException;
import java.io.StringReader;
import java.util.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class Lautturi {
public static void main(String[] args) throws Exception {
try
{
String xml = "<?xml version=\"1.0\"?>\r\n" +
"<catalog>\r\n" +
" <book id=\"bk101\">\r\n" +
" <author>Gambardella, Matthew</author>\r\n" +
" <title>XML Developer's Guide</title>\r\n" +
" <genre>Computer</genre>\r\n" +
" <price>44.95</price>\r\n" +
" <publish_date>2000-10-01</publish_date>\r\n" +
" <description>An in-depth look at creating applications \r\n" +
" with XML.</description>\r\n" +
" </book>\r\n" +
" <book id=\"bk102\">\r\n" +
" <author>Ralls, Kim</author>\r\n" +
" <title>Midnight Rain</title>\r\n" +
" <genre>Fantasy</genre>\r\n" +
" <price>5.95</price>\r\n" +
" <publish_date>2000-12-16</publish_date>\r\n" +
" <description>A former architect battles corporate zombies, \r\n" +
" an evil sorceress, and her own childhood to become queen \r\n" +
" of the world.</description>\r\n" +
" </book>\r\n" +
"</catalog>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document doc = builder.parse(is);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}