- Javax.xml.bind classes
- Home
- Binder
- DatatypeConverter
- JAXB
- JAXBContext
- JAXBElement
- JAXBElement.GlobalScope
- JAXBIntrospector
- Marshaller.Listener
- SchemaOutputResolver
- Unmarshaller.Listener
- Javax.xml.bind.util classes
- JAXBResult
- JAXBSource
- ValidationEventCollector
- Javax.xml.parsers classes
- DocumentBuilder
- DocumentBuilderFactory
- SAXParser
- SAXParserFactory
- Javax.xml.soap classes
- AttachmentPart
- MessageFactory
- MimeHeader
- MimeHeaders
- SAAJMetaFactory
- SOAPConnection
- SOAPConnectionFactory
- SOAPFactory
- SOAPMessage
- SOAPPart
- Javax.xml.validation classes
- Schema
- SchemaFactory
- TypeInfoProvider
- Validator
- ValidatorHandler
- Javax.xml.xpath classes
- XPathConstants
- XPathFactory
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
Javax.xml.parsers.DocumentBuilder.parse() Method
Description
The Javax.xml.parsers.DocumentBuilder.parse(File f) method parses the content of the given file as an XML document and return a new DOM Document object. An IllegalArgumentException is thrown if the File is null null.
Declaration
Following is the declaration for Javax.xml.parsers.DocumentBuilder.parse() method
public Document parse(File f)
Parameters
f − The file containing the XML to parse.
Return Value
This method returns a new DOM Document object.
Exception
IOException − If any IO errors occur.
SAXException − If any parse errors occur.
IllegalArgumentException − When f is null
Example
For our examples to work, a xml file named Student.xml is needed in our CLASSPATH. The contents of this XML are the following −
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes"?> <student id = "10"> <age>12</age> <name>Malik</name> </student>
The following example shows the usage of Javax.xml.parsers.DocumentBuilder.parse() method.
package com.tutorialspoint; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class DocumentBuilderDemo { public static void main(String[] args) { // create a new DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { // use the factory to create a documentbuilder DocumentBuilder builder = factory.newDocumentBuilder(); // create a new document from file File file = new File("Student.xml"); Document doc = builder.parse(file); // get the first element Element element = doc.getDocumentElement(); // get all child nodes NodeList nodes = element.getChildNodes(); // print the text content of each child for (int i = 0; i < nodes.getLength(); i++) { System.out.println("" + nodes.item(i).getTextContent()); } } catch (Exception ex) { ex.printStackTrace(); } } }
If we compile the code and execute it, this will produce the following result −
12 Malik
To Continue Learning Please Login
Login with Google