Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class Main {
    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        Document xmlDoc = docBuilder.parse(new File("sample.xml"));
        NodeList nodes = xmlDoc.getElementsByTagName("fr");
        for (int i = 0, length = nodes.getLength(); i < length; i++) {
            ((Element) nodes.item(i)).setTextContent("Modified");
        }
        xmlDoc.getDocumentElement().normalize();
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        DOMSource domSource = new DOMSource(xmlDoc);
        StreamResult result = new StreamResult(new File("sample.xml"));
        transformer.transform(domSource, result);
        System.out.println("Modification Done");
    }
}