This is an academic assignment and we are given an extremely large XML file with hundreds of entries like these. For each item we are supposed to list the Manager\'s ID, the
Or, using xml you might need to edit the initial content. I suggest the following approach
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class ReadXML {
public static void main(String[] args) {
try {
Document doc = getDocument("/home/abc/Test.xml");
System.out.println(getString(getNodeByName(doc,"item_list01")));
} catch (TransformerException | ParserConfigurationException | IOException | SAXException e) {
// Log e.printStackTrace();
}
}
private static Document getDocument(String filePath) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
return docBuilder.parse(filePath);
}
private static String getString(Node node) throws TransformerException {
StringWriter sw = new StringWriter();
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.transform(new DOMSource(node), new StreamResult(sw));
return sw.toString();
}
public static Node getNodeByName(Document doc, String nodeName) {
Node node = null;
for (int i = 0; i < doc.getDocumentElement().getChildNodes().getLength(); i++) {
if (!getTagName(doc, i).equals("#text")) {
for (int j = 0; j < getNodeName(doc, i).getChildNodes().getLength(); j++) {
if (getNodeName(doc, i, j).equalsIgnoreCase("item_list") && getNodeAttributes(doc,i,j).equalsIgnoreCase(nodeName)) {
node = getNodeName(doc, i);
}
}
}
}
return node;
}
private static String getTagName(Document doc, int i) {
return getNodeName(doc, i).getNodeName();
}
private static Node getNodeName(Document doc, int i) {
return (doc.getDocumentElement().getChildNodes().item(i));
}
private static String getNodeName(Document doc, int i, int j) {
return getNodeName(doc, i).getChildNodes().item(j).getNodeName();
}
private static String getNodeAttributes(Document doc, int i, int j) {
if(getNodeName(doc, i).getChildNodes().item(j).hasAttributes()){
return getNodeName(doc, i).getChildNodes().item(j).getAttributes().item(0).getNodeValue();
}
return "";
}
}