NIDHEESH KRISHNA NIDHEESH KRISHNA - 6 months ago 18
Java Question

reading xml file and parsers in java

I am trying to read a

XML
file using
FileInputStreamReader
class. But, when I try to read large
XML
files, some problems occur. Which java class is more suitable to read large
XML
files and what are the most efficient parsers to parse XML files?

Answer

I think that DOM parsing is a good way to parse XML files

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
Document doc = docBuilder.parse(yourFile);

in this way you start the parsing of your XML document, then you can modify the nodes and change what you want to change

TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(yourDoc);
StreamResult result = new StreamResult(yourFile);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);

And this second parte is to save all your changes. The "setOutputPropery" method is not mandatory, it's only used to give to the XML file a nice indent.

Comments