I was trying to search and replace an xml tag value using DOM. For example in my XML File i have a tag named teacher and inside that tag the text says "Teacher A". What i want the program to do is search for the tag value of "Teacher A" and change it to whatever i would like. I know i can get the tag name and the item #, but the task is to search and find the specific tag so that if there was to be changes made to the program this would be universal in finding and replacing the tag.
public static void reWrite() {
try {
String filepath = "school.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
// Get the staff element by tag name directly
Node staff = doc.getElementsByTagName("class").item(0);
for (int i = 0; i < 3; i++) {
/// append a new node to second student
Node Student1 = doc.getElementsByTagName("course").item(i);
Element dateOfBirth1 = doc.createElement("schoolBoard");
dateOfBirth1.appendChild(doc.createTextNode("BCS"));
Student1.appendChild(dateOfBirth1);
}
// update staff attribute
Element classElem = (Element) staff;
Node course = classElem.getElementsByTagName("course").item(0);
Element courseElem = (Element) course;
Node teacher = courseElem.getAttributeNode(filepath);
teacher.setTextContent("Mr.Theo");
//write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
System.out.println("Done");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}
}
XML File:
<?xml version="1.0" encoding="UTF-8"?>
<class>
<course>
<code>ICS4U</code>
<description>Computer Programming, Grade 12, College</description>
<teacher>Teacher A</teacher>
<fileType>unmodified</fileType>
</course>
<course>
<code>ENG4U1-01</code>
<description>English, Grade 12, College</description>
<teacher>Mr.Grabham</teacher>
<fileType>unmodified</fileType>
</course>
<course>
<code>MCV4U1-01</code>
<description>Calculus and Vectors, Grade 12, College</description>
<teacher>Mr.Newbury</teacher>
<fileType>unmodified</fileType>
</course>
</class>