Skip to content

Instantly share code, notes, and snippets.

@fileformat-blog-gists
Created March 26, 2025 12:13
Editing XML Files with Java
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class EditXML {
public static void main(String[] args) throws Exception {
File inputFile = new File("books.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("book");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
if (element.getAttribute("id").equals("1")) {
element.getElementsByTagName("price").item(0).setTextContent("24.99");
}
}
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("books.xml"));
transformer.transform(source, result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment