I want to read so many xml files in java. I have tried so many codes but none of
ID: 3544754 • Letter: I
Question
I want to read so many xml files in java. I have tried so many codes but none of them show how to get details of xml files by just reading a title or node of the file please help. just need a single code which can read many xml files.
here is the code i found:
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.events.XMLEvent;
import javax.xml.transform.stream.StreamSource;
public class XMLConcat {
public static void main(String[] args) throws Throwable {
File dir = new File("/tmp/rootFiles");
File[] rootFiles = dir.listFiles();
Writer outputWriter = new FileWriter("/tmp/bookstore.xml");
XMLOutputFactory xmlOutFactory = XMLOutputFactory.newFactory();
XMLEventWriter xmlEventWriter = xmlOutFactory.createXMLEventWriter(outputWriter);
XMLEventFactory xmlEventFactory = XMLEventFactory.newFactory();
xmlEventWriter.add(xmlEventFactory.createStartDocument());
xmlEventWriter.add(xmlEventFactory.createStartElement("", null, "rootSet"));
XMLInputFactory xmlInFactory = XMLInputFactory.newFactory();
for (File rootFile : rootFiles) {
XMLEventReader xmlEventReader = xmlInFactory.createXMLEventReader(new StreamSource(rootFile));
XMLEvent event = xmlEventReader.nextEvent();
// Skip ahead in the input to the opening document element
while (event.getEventType() != XMLEvent.START_ELEMENT) {
event = xmlEventReader.nextEvent();
}
do {
xmlEventWriter.add(event);
event = xmlEventReader.nextEvent();
} while (event.getEventType() != XMLEvent.END_DOCUMENT);
xmlEventReader.close();
}
xmlEventWriter.add(xmlEventFactory.createEndElement("", null, "rootSet"));
xmlEventWriter.add(xmlEventFactory.createEndDocument());
xmlEventWriter.close();
outputWriter.close();
}
}
Explanation / Answer
Below code can explain how to do things u need import java.io.*;import org.w3c.dom.*;import javax.xml.parsers.*;public class ReadCDATA {public static void main(String[] args) throws Exception {File file = new File("new.xml");DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();Document doc = builder.parse(file);NodeList nodes = doc.getElementsByTagName("messages");for (int i = 0; iRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.