Created
March 26, 2025 12:13
Editing XML Files with Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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