Java tutorial
//package com.java2s; /** * Copyright (c) {2003,2011} {openmobster@gmail.com} {individual contributors as indicated by the @authors tag}. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ import java.io.InputStream; import java.io.ByteArrayInputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; public class Main { private static DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); /** * Parses an input stream of xml data into a DOM tree * * @param is * @return the DOM tree */ public static Document parse(InputStream is) { try { Document document = null; DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(is); return document; } catch (Exception e) { throw new RuntimeException(e); } finally { if (is != null) { try { is.close(); } catch (Exception e) { throw new RuntimeException(e); } } } } /** * Parses a String of xml data into a DOM tree * * @param xml * @return the DOM tree */ public static Document parse(String xml) { InputStream is = null; try { Document document = null; DocumentBuilder builder = factory.newDocumentBuilder(); is = new ByteArrayInputStream(xml.getBytes()); document = builder.parse(is); return document; } catch (Exception e) { throw new RuntimeException(e); } finally { if (is != null) { try { is.close(); } catch (Exception e) { throw new RuntimeException(e); } } } } }