For reading XML file, there are several approaches to do so, if reading XML node element, it can use Java.xml in an old school approach.
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, TransformerException {
// Initial XML stream setting.
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("document.xml"));
// Loop all nodes inside Element "*".
NodeList nodeList = document.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE)
{ // do something with the current element
System.out.println(node.getNodeName());
}
}
}
Reference:
Revision at 01-Dec-2021:
It can read file and map to object directly with JAXB API.
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
public TestResult read(File file) {
try {
JAXBContext jaxbTestResultsContext = JAXBContext.newInstance(TestResults.class);
Unmarshaller jaxbTestResultUnmarshall = jaxbTestResultsContext.createUnmarshaller();
return (TestResults) jaxbTestResultUnmarshall.unmarshal(file);
} catch (JAXBException exception) {
throw new ReportResolveException("Error occurred when initial JAXB object with Test results.", exception);
}
}
Leave a Reply