import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; public class XmlParser { public static void main(String[] args) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse("file.xml"); // Do something with the parsed document object } catch (Exception e) { e.printStackTrace(); } } }
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.xml.sax.InputSource; public class XmlParser { public static void main(String[] args) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource inputSource = new InputSource(); inputSource.setCharacterStream(new StringReader(xmlSource)); Document document = builder.parse(inputSource); // Do something with the parsed document object } catch (Exception e) { e.printStackTrace(); } } }In this example, we first create a DocumentBuilderFactory and DocumentBuilder object. We then create a new InputSource with the XML string we want to parse. We then call the builder.parse() method with the InputSource object. The parsed document object is then returned and can be used to access the XML data. The javax.xml.parsers package is part of the Java API for XML Processing (JAXP) library.